Python列表函数是列表操作中常用的工具,下面是一些常用的列表函数及其使用方法:
1. `len(list)`:返回列表中元素的个数。
```python
list1 = [1, 2, 3, 4]
print(len(list1)) 输出:4
2. `max(list)`:返回列表中最大的元素。
```python
list1 = [1, 2, 3, 4]
print(max(list1)) 输出:4
3. `min(list)`:返回列表中最小的元素。
```python
list1 = [1, 2, 3, 4]
print(min(list1)) 输出:1
4. `list(seq)`:将元组转换为列表。
```python
tuple1 = (1, 2, 3, 4)
list1 = list(tuple1)
print(list1) 输出:[1, 2, 3, 4]
5. `list.append(obj)`:在列表末尾添加一个元素。
```python
list1 = [1, 2, 3]
list1.append(4)
print(list1) 输出:[1, 2, 3, 4]
6. `list.count(obj)`:统计某个元素在列表中出现的次数。
```python
list1 = [1, 2, 3, 2, 4]
count = list1.count(2)
print(count) 输出:2
7. `list.extend(seq)`:在列表末尾一次性追加另一个序列中的多个值。
```python
list1 = [1, 2, 3]
list1.extend([4, 5, 6])
print(list1) 输出:[1, 2, 3, 4, 5, 6]
8. `list.index(obj)`:从列表中找出某个值第一个匹配项的索引位置。
```python
list1 = [1, 2, 3, 4]
index = list1.index(3)
print(index) 输出:2
9. `list.insert(index, obj)`:将对象插入列表的指定位置。
```python
list1 = [1, 2, 3]
list1.insert(1, 1.5)
print(list1) 输出:[1, 1.5, 2, 3]
10. `list.pop([index=-1])`:移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
```python
list1 = [1, 2, 3]
popped_element = list1.pop()
print(popped_element) 输出:3
print(list1) 输出:[1, 2]
11. `list.remove(obj)`:移除列表中某个值的第一个匹配项。
```python
list1 = [1, 2, 3, 2]
list1.remove(2)
print(list1) 输出:[1, 3, 2]
12. `list.reverse()`:反向列表中元素。
```python
list1 = [1, 2, 3, 4]
list1.reverse()
print(list1) 输出:[4, 3, 2, 1]
13. `list.sort(key=None, reverse=False)`:对原列表进行排序。
```python
list1 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
list1.sort()
print(list1) 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
14. `list.clear()`:清空列表。
```python
list1 = [1, 2, 3, 4]
list1.clear()
print(list1) 输出:[]
15. `list.copy()`:复制列表。