目录
list方法的使用
append(self, object, /)
Append object to the end of the list.
在尾部追加 返回返回空列表
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
clear(self, /)
Remove all items from list.
清空列表
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
copy(self, /)
Return a shallow copy of the list.
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
count(self, value, /)
Return number of occurrences of value.
计数
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
extend(self, iterable, /)
Extend list by appending elements from the iterable.
将列表元素(或任何可迭代的元素)添加到当前列表的末尾
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
index
Return first index of value.
Raises ValueError if the value is not present.
返回具有指定值的第一个元素的索引
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
insert(self, index, object, /)
Insert object before index.
返回具有指定值的第一个元素的索引
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
pop(self, index=-1, /)
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
删除指定位置的元素
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
remove(self, value, /)
Remove first occurrence of value.
Raises ValueError if the value is not present.
删除具有指定值的项目
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
reverse(self, /)
Reverse IN PLACE.
颠倒列表的顺序
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
sort(self, /, *, key=None, reverse=False)
Sort the list in ascending order and return None.
# *后面的必须以赋值号来传入参数
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
order of two equal elements is maintained).
If a key function is given, apply it once to each list item and sort them,
ascending or descending, according to their function values.
The reverse flag can be set to sort in descending order.
对列表进行排序
list4 = [1, 4, 7, 9, 8]
list4.sort()
# print(list4)
def get_last_char(str_data):
return str_data[-1], str_data[-2], str_data[-3]
# return str_data[2]
fruit_list = ["banana", "durian", "pineapple", "cherry", "strawberry", "kiwifruit", "peach", "grape"]
# fruit_list.sort()
fruit_list.sort(key=get_last_char)
# print(fruit_list)