(1)list 列表操作包含以下函数。
- 比较两个列表的函数, 以前的版本有cmp方法, 3. 之后取消了,但是可以直接用“>”,“<”, 或者“=”, 来直接比较,这种方法对于字符串也是适用的
- len(list):列表元素个数,也适用于元组,字符串
- max(list):列表元素的最大值, 也适用于元组,字符串
- min(list):列表元素的最小值, 也适用于元组,字符串
- list(seq): 将元组转换成列表。
(2) liest列表操作方法。
- list.append(obj):在列表末尾添加新的对象
- list.count(obj):统计某个元素在列表中出现的次数
- list.extend(seq):在列表末尾一次追加另一个序列中的多个值(用新列表扩展原来的列表)
- liest.index(obj):从列表中找出某个值第一个匹配项的索引位置
- list.insert(index,obj):将对象插入列表的指定位置
- list.pop(obj=list[-1]):移除列表中的一个元素(默认是最后一个元素),不过也可以指定
- list.remove(obj):移除列表中的某个值的第一个匹配项
- list.reverse():反向列表中的元素
- list.sort(key = None, reverse = False): 对列表进行排序,reverse参数有False和True决定排序是由小到大还是由大到小,https://docs.python.org/3.3/howto/sorting.html
Key Functions
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
For example, here’s a case-insensitive string comparison:
>>>
>>>
sorted(
"This is a test string from Andrew"
.split(), key
=
str
.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
A common pattern is to sort complex objects using some of the object’s indices as keys. For example:
>>>
>>> student_tuples
= [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>>
sorted(student_tuples, key
=
lambda student: student[
2])
# sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]