python 包含6种内建序列:列表 元组 字符串 Unicode字符串 buffer对象 xrange对象
有几种操作适用于所有序列,包括索引、切片、相加、相乘和成员资格检查。另外,Python还提供了一些内置函数,可用于确定序列的长度以及找出序列中最大和最小的元素,还有迭代。
索引
greeting=‘hello’
print(greeting[3]) # l
切片
numbers=[1,2,3,4,5,6,7,8,9,10]
#numbers=[p for p in range(1,11)]
print(numbers[3:6])
print(numbers[0:1])
print(numbers[-3:-1])
print(numbers[-3:0])
print(numbers[:3])
print(numbers[:])
print(numbers[0:10:2])
print(numbers[::4])
print(numbers[8:3:-1])
print(numbers[10:0:-2])
print(numbers[5::-2])
print(numbers[:5:-2])
序列相加
a=[1,2,3]+['2','5',6]
print(a) #[1, 2, 3, ‘2’,‘5’ , 6]
c='hello'+' '+'world'
print(c) #hello world
e=[1,2]+'hello'
print(f) #can only concatenate list (not "str") to list
不同类型的序列不能相加
乘法
[42]*2 #[42,42]
'python'*2 #'pythonpython'
(None,)*2 #(None,None)
成员资格
in 和 not in
长度,最小值 和最大值
迭代
方法__iter__返回一个迭代器,它是包含__next__的对象,调用__next__时,迭代器返回下一个值,也可用next()代替。
##内置对象iter
# it=iter('adasdad')
# print(next(it))
# print(next(it))
#内置对象filter
from time import time
import math
def is_prime(x):
return 0 not in [x % i for i in range(2, int(math.sqrt(x)) + 1)]
t = time()
p = list(filter(is_prime, range(100, 500)))
print (p)