Python 中列表中的元素重复
pythonserver side programmingprogramming更新于 2025/11/23 17:48:17
有些情况下我们需要重复列表中的值。在 Python 中,可以通过以下方式实现值的重复。
使用嵌套 for 循环
这是一种直接的方法,其中选取每个元素,通过内部 for 循环创建其副本,然后将它们都传递给外部 for 循环。
示例
# 给定列表
listA = ['Mon', 'Tue', 9, 3, 3]
print("Given list : ",listA)
# 为每个元素添加另一个元素
Newlist = [i for i in listA for n in (0, 1)]
# 结果
print("New list after duplication: ",Newlist)
输出
运行上述代码得到以下结果 −
Given list : ['Mon', 'Tue', 9, 3, 3] New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]
使用 itertools
itertools 模块处理可迭代对象中的数据操作。这里我们应用 chain.from_iterables,它
示例
import itertools
# 给定列表
listA = ['Mon', 'Tue', 9, 3, 3]
print("Given list : ",listA)
# 为每个元素添加另一个元素
Newlist = list(itertools.chain.from_iterable([n, n] for n in listA))
# 结果
print("New list after duplication: ",Newlist)
输出
运行上述代码得到以下结果 −
Given list : ['Mon', 'Tue', 9, 3, 3] New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]
使用reduce
reduce函数将作为参数传递给它的特定函数应用于作为第二个参数传递给它的所有列表元素。我们将其与add函数一起使用,该函数添加列表中存在的每个元素的重复元素。
示例
from functools import reduce
from operator import add
# 给定列表
listA = ['Mon', 'Tue', 9, 3, 3]
print("Given list : ",listA)
# 为每个元素添加另一个元素
Newlist = list(reduce(add, [(i, i) for i in listA]))
# 结果
print("New list after duplication: ",Newlist)
输出
运行上述代码得到以下结果 −
Given list : ['Mon', 'Tue', 9, 3, 3] New list after duplication: ['Mon', 'Mon', 'Tue', 'Tue', 9, 9, 3, 3, 3, 3]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

