Python 列表操作指南2

发布时间 2023-10-03 20:28:49作者: 小万哥丶

将元组的元素添加到列表中:

thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

remove() 方法用于移除指定的项目。

示例,移除 "banana":

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

如果存在多个具有指定值的项目,则 remove() 方法将删除第一个出现的项目:

示例,移除第一个出现的 "banana":

thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)

pop() 方法用于移除指定的索引。

示例,移除第二个项目:

thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

如果不指定索引,pop() 方法将移除最后一个项目。

示例,移除最后一个项目:

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

使用 del 关键字也可以移除指定的索引:

示例,移除第一个项目:

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

del 关键字还可以完全删除列表。

示例,删除整个列表:

thislist = ["apple", "banana", "cherry"]
del thislist

clear() 方法用于清空列表。列表仍然存在,但没有内容。

示例,清空列表内容:

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

通过列表进行循环,您可以使用 for 循环遍历列表项:

示例,逐个打印列表中的所有项目:

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

您还可以通过引用它们的索引编号来遍历列表项。使用 range() 和 len() 函数创建一个合适的可迭代对象。

示例,通过引用它们的索引编号打印所有项目:

thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
  print(thislist[i])

上面示例中创建的可迭代对象是 [0, 1, 2]。您可以使用 while 循环遍历列表项。使用 len() 函数来确定列表的长度,然后从 0 开始,通过引用它们的索引遍历列表项。记得在每次迭代后将索引增加 1。

示例,使用 while 循环打印所有项目,通过遍历所有索引编号:

thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
  print(thislist[i])
  i = i + 1

列表推导式在您想要基于现有列表的值创建新列表时提供了更短的语法。

示例:假设有一个水果列表,您想要一个新列表,其中仅包含名称中带有字母 "a" 的水果。

如果不使用列表推导式,您将不得不编写一个带有条件测试的 for 语句:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
  if "a" in x:
    newlist.append(x)

print(newlist)

使用列表推导式,您只需要一行代码就可以完成所有操作:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

语法

newlist = [expression for item in iterable if condition == True]

返回值是一个新列表,不会改变旧列表。条件就像一个筛选器,只接受计算结果为 True 的项目。

示例,仅接受不是 "apple" 的项目:

newlist = [x for x in fruits if x != "apple"]

条件 if x != "apple" 会对除了 "apple" 之外的所有元素返回 True,使新列表包含除 "apple" 之外的所有水果。条件是可选的,可以省略:

示例,没有 if 语句:

newlist = [x for x in fruits]

可迭代对象可以是任何可迭代的对象,如列表、元组、集合等。

示例,您可以使用 range() 函数创建一个可迭代对象:

newlist = [x for x in range(10)]

同样的示例,但带有条件:

示例,只接受小于 5 的数字:

newlist = [x for x in range(10) if x < 5]

表达式是迭代中的当前项目,但它也是结果,您可以在最终成为新列表中的列表项之前对其进行操作:

示例,将新列表中的值设置为大写:

newlist = [x.upper() for x in fruits]

您可以将结果设置为您喜欢的任何内容:

最后

为了方便其他设备和平台的小伙伴观看往期文章,链接奉上:

公众号搜索Let us Coding知乎开源中国CSDN思否掘金InfoQ简书博客园慕课51CTOhelloworld腾讯开发者社区阿里开发者社区

看完如果觉得有帮助,欢迎点赞、收藏关注