之前我也总结过一些用法,但是这些东西看起来不够公式化。今天无意间看到了python文档中得详细介绍。在这里搬运一下。
在python中,list、tuple、range都被成为sequence(序列)
str也被看做是特殊的sequence
list tuple range操作符表
我找重要的几个翻译一下:
操作符 | 结果 |
---|---|
x in s | x是否在s中 |
s+t | 两个序列的串联(非常有用~) |
n*s | 相当于给s加了n次 |
s[i] | 取下标,这个没什么好说的 |
s[i:j] | 切片,注意切出来的是从s[i]到s[j-1] |
min(s) | 最小值 |
s.index(x) | 有点像find(),返回第一个x的下标 |
s.count(x) | 返回s中x的个数 |
专属于list的操作
有一些操作是list专属的(range、tuple作为不可变的序列)
比较重要的方法应该有:
操作符 | 结果 |
---|---|
s[i]=x | 改变值 |
del s[i,j] | 等同于s[i:j]=[],另还可以del s[i:j:k] |
s.append(x) | 添加元素,但是现在看来可以用s+=[x]的形式代替 |
s.extend(t) | 两个序列的合并,也可以用s+=t来代替 |
s.insert(i,x) | 特定位置插入 |
s.pop(i) | 特定位置pop出 |
s.remove(x) | 删除第一个x |
s.reverse() | 反转,也比较有用 |
s.copy() | 这个需要仔细甄别 |
在python中类似这样a=[0,1,2] b=a
的操作导致的结果是b只是a的一个引用(或者说别名),正确的方法是b=a.copy()
或者b=a[:]
list的构造方法
- Using a pair of square brackets to denote the empty list: []
- Using square brackets, separating items with commas: [a], [a, b, c]
- Using a list comprehension: [x for x in iterable]
- Using the type constructor: list() or list(iterable)
list(‘abc’) returns [‘a’, ‘b’, ‘c’] and list( (1, 2, 3) ) returns [1, 2, 3] 分解字符串的好方法。字符串因为也是特殊的迭代器,所以可以转换成list。
iterable对象
stackoverflow中的回答
- 实现了 iter() 或 getitem() 方法的对象;(常用)
- 实现了 .next() 的可调用实体。
sort
sort(*, key=None, reverse=None)
This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).
str.split()方法也返回的是一个list
这个方法可以很方便得用来分解字符串。
>>> string
'son of bitch'
>>> a=string.split()
>>> a
['son', 'of', 'bitch']