Python - list (list) common operations

list creation

To create a list, simply enclose the different data items separated by commas in square brackets. Any type of data can be placed in the list.
Format:列表名 = [列表项1, 列表项2 ... 列表项n]

# 创建一个空列表
list_00 = []

# 创建一个带有元素的一维列表
list_01 = ["六", 6, 6.88, True, None, {
    
    "name": "彦祖"}]

# 创建一个多维列表(以二维为示例)
list_02 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

Add, delete, modify and check the list

Inquire

list = ['red', 'green', 'blue', 'yellow', 'white', 'black']

# 列表索引从 0 开始,第二个索引是 1,依此类推
print(list[0])
print(list[1])
print(list[2])
# 输出:
red
green
blue

# 索引也可以从尾部开始,最后一个元素的索引为 -1,往前一位为 -2,以此类推
print(list[-1])
print(list[-2])
print(list[-3])
# 输出:
black
white
yellow

# 使用下标索引来访问列表中某个下标范围的值,包头不包尾
print(list[2:5])
# 输出:
['blue', 'yellow', 'white']

renew

list = ['乐昌', '测试工程师', 18, '男', True]
print("第三个元素为 : ", list[2])
list[2] = 24	# 更新小标为2的元素为 24
print("更新后的第三个元素为 : ", list[2])

# 输出
第三个元素为 :  18
更新后的第三个元素为 :  24

Increase

append()method to add list items

list_01 = ['乐昌', '测试工程师', 18]
list_01.append('男')
print(list_01)
# 输出
['乐昌', '测试工程师', 18, '男']

delete

delstatement to delete elements of a list

list_01 = ['乐昌', '测试工程师', 18]
print("删除前:", list_01)
del list_01[1]
print("删除后:", list_01)
# 输出:
删除前:['乐昌', '测试工程师', 18]
删除后:['乐昌', 18]

Deduplication

list_01 = ['乐昌', '测试工程师', 18, '乐昌', '测试工程师', 18]

# 方式一:遍历整个列表,将每个元素首次出现放入新列表
res = []
for i in list_01:
    if i not in res:
        res.append(i)
print(res)		# ['乐昌', '测试工程师', 18]

# 方式二:使用列表推导式编列整个列表,将每个元素首次出现放入新列表
res = []
[res.append(i) for i in list_01 if i not in res]
print(res)		# ['乐昌', '测试工程师', 18]

# 方式三:使用 set(),最流行的方法。这种方法的缺点是set后列表中元素的顺序和原来不一样
list_01 = list(set(list_01))
print(list_01)		# ['乐昌', '测试工程师', 18]

# 方式四:enumerate(),此方法保持列表中元素的顺序
res = [i for n, i in enumerate(list_01) if i not in list_01[:n]]
print(res)		# ['乐昌', '测试工程师', 18]

# 方法五:使用 collections.OrderedDict.fromkeys()
# 这是完成特殊任务的最快方式。它首先删除列表中的重复项并返回一个字典,最后将其转换为列表。此方法也可用于字符串,之后列表中元素的顺序也发生了变化。
res = list(OrderedDict.fromkeys(list_01))
print(res)		# ['乐昌', '测试工程师', 18]

# 方法六:处理嵌套列表中的重复元素
# 用于多维列表(列表嵌套)重复元素移除。这里假设列表(也是一个列表)中具有相同元素(但不一定是相同顺序)的元素被认为是重复的。然后使用下面的 set() + sorted() 方法完成任务。
test_list = [[1, 2, 3], [3, 2, 1], [3, 2, 1], [1, 2, 3], [-3, -2, -1]]
res = list(set(tuple(sorted(sub)) for sub in test_list))
print(res)		# [(1, 2, 3), (-3, -2, -1)]

list operator

  • len(list): Get the length of the list (the number of elements the list contains).
  • list + list: Combine two lists into a new list.
  • list * n: Add n identical list elements to the list.
  • x in list: Determine whether the element x exists in the list.
  • for x in list: print(x, end=" "): Loop through the output list elements.
  • operator.eq(list01,list02): Check if two lists are equal
import operator

list_01 = ['乐昌', '测试工程师', 18]

print(len(list_01))             # 3

new_list = list_01 + list_01
print(new_list)                 # ['乐昌', '测试工程师', 18, '乐昌', '测试工程师', 18]

new_list02 = list_01 * 2
print(new_list02)               # ['乐昌', '测试工程师', 18, '乐昌', '测试工程师', 18]

print('测试工程师' in list_01)   # True

for x in list_01 : print(x, end=" ")    # 乐昌 测试工程师 18

print(operator.eq(new_list, new_list02))    # True

List functions & methods

function

  • len(list): the number of list elements
  • max(list): returns the maximum value of list elements
  • min(list): returns the minimum value of a list element
  • list(seq): convert tuple to list
list_01 = [5, 8, 18]        
print(len(list_01))         # 3
print(max(list_01))         # 18
print(min(list_01))         # 5
print(list((1, "2", 3)))    # [1, '2', 3]

method

method illustrate
list.append(obj) Add new object at the end of the list
list.count(obj) Count the number of times an element appears in a list
list.extend(seq) Append multiple values ​​from another sequence in one go to the end of a list (extending the original list with the new list)
list.index(obj) Find the index position of the first occurrence of a value in a list
list.insert(index, obj) insert object into list
list.pop([index=-1]) Remove an element in the list (the last element by default), and return the value of the element
list.remove(obj) removes the first occurrence of a value in a list
list.reverse() reverse list element
list.sort( key=None, reverse=False) Sort the original list
list.clear() clear the list
list.copy() copy list


list_01 = ['乐昌', '测试工程师', 18]


list_01.append("乐昌")
print(list_01)		# ['乐昌', '测试工程师', 18, '乐昌']

list_01.count("乐昌")
print(list_01)		# 2

list_01.extend(["1", 2, 3])
print(list_01)		# ['乐昌', '测试工程师', 18, '乐昌', '1', 2, 3]

index_01 = list_01.index("测试工程师")
print(index_01)		# 1

list_01.insert(1, "666")
print(list_01)		# ['乐昌', '666', '测试工程师', 18, '乐昌', '1', 2, 3]

list_01.pop(5)
print(list_01)		# ['乐昌', '666', '测试工程师', 18, '乐昌', 2, 3]

list_01.remove("乐昌")
print(list_01)		# ['666', '测试工程师', 18, '乐昌', 2, 3]

list_01.reverse()
print(list_01)		# [3, 2, '乐昌', 18, '测试工程师', '666']

list_02 = [3, 2, 1]
list_02.sort()
print(list_02)		# [1, 2, 3]

list_03 = list_01.copy()
print(list_03)		# [3, 2, '乐昌', 18, '测试工程师', '666']

Guess you like

Origin blog.csdn.net/weixin_44988085/article/details/129322143