operation | result |
---|---|
x in s | True if an item of s is equal to x, else False |
x not in s | False if an item of s is equal to x, else True |
s + t | the concatenation of s and t |
s * n or n * s | equivalent to adding s to itself n times |
s[i] | ith item of s, origin 0 |
s[i: j] | slice of s from i to j |
s[i: j: k] | slice of s from i to j with step k |
len(s) | length of s |
min(s) | smallest item of s |
max(s) | largest item of s |
s.index(x[, i[, j]]) | index of the first occurrence of x in s (at or after index i and before index j) |
s.count(x) | total number of occurrences of x in s |
operation | result |
---|---|
s[i] = x | item i of s is replaced by x |
s[i: j] = t | slice of s from i to j is replaced by the contents of the iterable t |
s[i: j: k] = t | the elements of s[i:j:k] are replaced by those of t |
del s[i:j] | same as s[i:j] = [] |
del s[i:j:k] | removes the elements of s[i:j:k] from the list |
s.append(x) | appends x to the end of the sequence (same as s[len(s):len(s)] = [x]) |
s.clear() | removes all items from s (same as del s[:]) |
s.copy() | creates a shallow copy of s (same as s[:]) |
s.extend(t) or s += t | extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t) |
s *= n | updates s with its contents repeated n times |
s.insert(i, x) | inserts x into s at the index given by i (same as s[i:i] = [x]) |
s.pop() or s.pop(i) | retrieves the item at i and also removes it from s
The optional argument i defaults to -1, so that by default the last item is removed and returned. |
s.remove(x) | remove the first item from s where s[i] is equal to x |
s.reverse() | reverses the items of s in place |
nums = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
nums = [0] * 10
letters = ["a", "b", "c", "d", "e", "f"] # a b c f, s, t = letters
# a b f, s, *other = letters # a f f, *other, s = letters
获取数据;但是无法直接获取数据对应的索引
for letter in letters: print(letter, end=" ")
内置函数
将一个序列转换枚举对象;该对象每次迭代时,返回一个包含索引和数据的元组 tuple
转换时,可以指定索引起始值
enumerate(sequence, start)
# [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')] list(enumerate(letters)) # [(2, 'a'), (3, 'b'), (4, 'c'), (5, 'd'), (6, 'e'), (7, 'f')] list(enumerate(letters, start=2))
普通遍历使用
for index, letter in enumerate(letters, start=2): print(index, letter)
内置函数
像拉链 zip一样,将2个或多个序列糅合|关联到一起
多个序列迭代时候,分别获取对应位置的数据组成一个元组 tuple
序列的长度尽量相同/匹配,否则需要遵循一定的原则处理
如果有个数值序列,相当于指定了数据的索引
nums = [0, 1, 2, 3, 4, 5] letters = ["a", "b", "c", "d", "e", "f"]
得到元组 (0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e') (5, 'f')
for letter in zip(nums, letters): print(letter)
得到具体的索引和数据
for num, letter in zip(nums, letters): print(num, letter)