摘要:mixed_list = [1, True, [1, 2, 3], {"name":"Alex", "age":12}, (1, 2, 3), "Bob"]
列表允许在一个变量中存储多个值。例如,我们希望将用户的 ID 存储在变量中,因此我们的列表将如下所示:user_id
user_ids = [11, 22, 33, 44, 55]在列表中允许混合不同类型的对象,换句话说,列表是异构集合。
mixed_list = [1, True, [1, 2, 3], {"name":"Alex", "age":12}, (1, 2, 3), "Bob"]在上面的列表中,储了各种类型的数据,包括数字、字符串、字典等。
append方法:这种方法允许在给定列表的末尾添加一个元素。它就地修改了原始列表。
ages = [10,15,18]ages.append(20)2. 方法:extend
通过追加可迭代对象中的元素来扩展列表。它接受一个可迭代对象(例如,列表、元组或字符串)并将其元素添加到列表的末尾。
shopping_cart = ["apple", "butter", "cheese"]additional_items = ["meat", "coffee"]shopping_cart.extend(additional_items)print(shopping_cart)# ['apple', 'butter', 'cheese', 'meat', 'coffee']3. 方法:insert
在列表中的指定索引处插入元素。此方法将现有元素向右移动。
feature_list = ["authentication", "authorization", "logging"]new_feature = "encryption"feature_list.insert(1, new_feature)# Result: ["authentication", "encryption", "authorization", "logging"]4. 方法:remove
从列表中删除元素的第一个匹配项。如果该元素不存在,则引发 .ValueError
to_do_list = ["edit video", "write a blog post", "email to the client", "attend to the meeting"]to_do_list.remove("edit video")# result: ["write a blog post", "email to the client", "attend to the meeting"]5. 方法:pop
该方法删除并返回指定默认值为 -1 的元素。如果未提供 ,则删除并返回最后一个元素。popindexindex
stack = [1, 2, 3, 4, 5]popped_item = stack.pop# Result: stack = [1, 2, 3, 4], popped_item = 56. 方法:index
该方法返回指定值第一次出现时的位置。如果列表中不存在指定的元素,则返回 .indexValueError
browsers = ["Google Chrome", "Firefox", "Safari", "Opera"]firefox = browsers.index("Firefox")# 1explorer = browsers.index("Internet Explorer")# ValueError: 'Internet Explorer' is not in list7. 方法:count
从方法的名称可以看出,它返回给定列表中元素的出现次数。
grades = ['A', 'B', 'A', 'C', 'B', 'A', 'D', 'A', 'F', 'B']num_of_A_grades = grades.count('A')# 48. 方法:sort
按升序对列表的元素进行排序。我们可以使用该参数来指定自定义排序函数,并按降序排序。keyreverse=True
prices = [100, 50, 78, 98, 34, 21, 67]prices.sort# Result: [21, 34, 50, 67, 78, 98, 100]tasks = [("TaskA", 2), ("TaskB", 1), ("TaskC", 3)]tasks.sort(key=lambda x: x[1]) # Sort based on priority (second element)# Result: [("TaskB", 1), ("TaskA", 2), ("TaskC", 3)]9. 方法:reverse
该方法反转列表的元素。reverse
message_history = ["message1", "message2", "message3", "message4"]message_history.reverse# ['message4', 'message3', 'message2', 'message1']10. 方法:copy
返回给定列表的浅表副本。该方法使用相同的元素创建新列表,但对复制列表中元素的更改不会影响原始列表,反之亦然。copy
config_settings = ["setting1", "setting2", "setting3"]config_backup = config_settings.copy# Result: config_settings and config_backup are distinct lists with the same elements来源:自由坦荡的湖泊AI
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!