Python: 11 built-in methods for lists

foreword

In actual development, it is often necessary to store a set of (more than one) data for later use in code. Arrays are used in VBA to store multiple data

Together, each element in the array can be accessed via the array subscript. There are no arrays in Python, but the more powerful list is added. Below is the list of

The setup method is introduced.

insert image description here

通过dir(list)可以查看列表的属性和内置方法。
print(dir(list))
Python学习交流Q群:906715085###
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
可以看出,列表有11个内置方法。
1  append()、extend()、insert()方法

2  clear()、remove()、pop()方法 

3  count()、index()方法

4  sort()、reverse()方法

5  copy()方法 

insert image description here

1 append (), extend (), insert () method

list.append(obj)

obj – represents the data to add to the end of the list, it can be a single element, a list, a tuple, etc.

Append elements at the end of the list.

Python学习交流Q群:906715085###
list1 = ['Python', 'C++', 'Java']

# 追加元素
list1.append('PHP')
print(list1)

#追加元组,整个元组被当成一个元素
t = ('JavaScript', 'C#', 'Go')
list1.append(t)
print(list1)

#追加列表,整个列表被当成一个元素
list1.append(['Ruby', 'SQL'])
print(list1)
['Python', 'C++', 'Java', 'PHP']
['Python', 'C++', 'Java', 'PHP', ('JavaScript', 'C#', 'Go')]
['Python', 'C++', 'Java', 'PHP', ('JavaScript', 'C#', 'Go'), ['Ruby', 'SQL']]
	list.extend(seq)

seq – a list of elements, which can be a list, a tuple, a set, or a dictionary. If it is a dictionary, only the key will be added as an element to the end of the original list.

Appends multiple values ​​from another sequence at the end of a list (extends the original list with the new list).

The difference between extend() and append() is that extend() does not treat the list or tuple as a whole, but adds the elements they contain to the list one by one.

Python学习交流Q群:906715085###
list2 = ['Python', 'C++', 'Java']

# 追加元素
list2.extend('C')
print(list2)

# 追加元组,元祖被拆分成多个元素
t = ('JavaScript', 'C#', 'Go')
list2.extend(t)
print(list2)

# 追加列表,列表被拆分成多个元素
list2.extend(['Ruby', 'SQL'])
print(list2)
['Python', 'C++', 'Java', 'C']
['Python', 'C++', 'Java', 'C', 'JavaScript', 'C#', 'Go']
['Python', 'C++', 'Java', 'C', 'JavaScript', 'C#', 'Go', 'Ruby', 'SQL']

list.insert(index, obj)

index – the index position where the object obj needs to be inserted.

obj – The object to insert into the list.

Inserts the specified object at the specified position in the list.

list3 = ['Google', 'Runoob', 'Taobao']

list3.insert(1, 'Baidu')
print ('列表插入元素后为 : ', list3)
列表插入元素后为 : ['Google', 'Baidu', 'Runoob', 'Taobao']

insert image description here

2 clear (), remove (), pop () methods

list.clear()

Empty the list, similar to del a[:].

list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list2 = ['Google', 'Runoob', 'Taobao', 'Baidu']

list1.clear()
del list2[:]

print("列表清空后的list1: ", list1)
print("列表清空后的list2: ", list2)
列表清空后的list1: []
列表清空后的list2: []
list.remove(obj)

Removes the first occurrence of a value in the list.

list1 = ['Google', 'Baidu', 'Runoob', 'Taobao', 'Baidu']

list1.remove('Taobao')
print ("列表现在为 : ", list1)

list1.remove('Baidu')
print ("列表现在为 : ", list1)
列表现在为 : ['Google', 'Baidu', 'Runoob', 'Baidu']
列表现在为 : ['Google', 'Runoob', 'Baidu']
list.pop([index=-1])

index – an optional parameter. The index value of the list element to be removed cannot exceed the total length of the list. The default is index=-1, and the last list value is deleted.

Removes an element from the list (the last element by default) and returns the value of that element.

list1 = ['Google', 'Runoob', 'Taobao']

print(list1.pop())
print ("列表现在为 : ", list1, end="\n\n")

print(list1.pop(0))
print ("列表现在为 : ", list1)
Taobao
列表现在为 : ['Google', 'Runoob']

Google
列表现在为 : ['Runoob']

3 count(), index() methods

list.count(obj)

Count the number of times an element appears in a list.

aList = [123, 'Google', 'Runoob', 'Taobao', 123];

print ("123 元素个数 : ", aList.count(123))
print ("Runoob 元素个数 : ", aList.count('Runoob'))
123 元素个数 : 2
Runoob 元素个数 : 1
list.index(x[, start[, end]])

start -- 可选,查找的起始位置。

end --  可选,查找的结束位置。

从列表中找出某个值第一个匹配项的索引位置,如果没有找到对象则抛出异常。
list1 = ['Google', 'Runoob', 'Taobao', 'Runoob', 'QQ']

print ('Runoob 索引值为', list1.index('Runoob'))
print ('Runoob 索引值为', list1.index('Runoob',2,4))
Runoob 索引值为 1
Runoob 索引值为 3

insert image description here

4 sort(), reverse() methods

list.sort( key=None, reverse=False)

key -- 指定在进行比较前要在每个列表元素上调用的函数(或其他可调用对象)。

reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
aList = ['Google', 'Runoob', 'Taobao', 'Facebook']

aList.sort()    # 升序排列
print("List : ", aList)
List : ['Facebook', 'Google', 'Runoob', 'Taobao']
# 获取序列的第二个元素
def take_second(elem):
    return elem[1]

# 列表
list1 = [(2, 2), (3, 4), (4, 1), (1, 3)]

# 指定第二个元素,升序排列
list1.sort(key=take_second)

# 输出类别
print('排序后的列表:', list1)
排序后的列表:[(4, 1), (2, 2), (1, 3), (3, 4)]

For sorting, there is also a sorted() built-in function in Python. The difference between the two is that the list.sort() method directly modifies the original list (and returns None to avoid confusion).

confusion), while the sorted() built-in function returns a new sorted list.

student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10)]

new_tuples = sorted(student_tuples, key=lambda student: student[2])   # sort by age

print("排序前:",student_tuples)
print("排序后:",new_tuples)
排序前:[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
排序后:[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
list.reverse()

对列表的元素进行反向排序。
list1 = ['Google', 'Runoob', 'Taobao', 'Baidu']
list1.reverse()
print ("列表反向排序后: ", list1)
列表反向排序后: ['Baidu', 'Taobao', 'Runoob', 'Google']

5 copy() method

list.copy()

复制列表,类似于 a[:]。

Note: The copy principle followed by the list.copy() method is a shallow copy, that is, only the parent object is copied, and the child objects inside the object are not copied. About deep copy and shallow copy

For more information about Bei, see

Extended reading at the end of the article [1].

a = [1, 2, [3, 4], 5, 6]
b = a.copy()

a.append(7)
a[2][1] = 10

print("a = ", a)
print("b = ", b)
a = [1, 2, [3, 10], 5, 6, 7]
b = [1, 2, [3, 10], 5, 6]

It can be seen that the new element in list a has no effect on list b; but if the list object in a is modified, it will also affect b.

insert image description here

Guess you like

Origin blog.csdn.net/xff123456_/article/details/124344595