Python|列表中的元素重复
有时我们需要在列表中为几个不同的实用程序添加重复值。在日常编程中有时需要这种类型的应用程序。让我们讨论将数字的克隆添加到其下一个位置的某些方法。
方法#1:使用列表推导
在这个方法中,我们只是为每个值迭代循环两次并添加到所需的新列表中。这只是朴素方法的一种简写替代方案。
# Python3 code to demonstrate
# to perform element duplication
# using list comprehension
# initializing list
test_list = [4, 5, 6, 3, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension
# to perform element duplication
res = [i for i in test_list for x in (0, 1)]
# printing result
print ("The list after element duplication " + str(res))
输出 :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]
方法 #2:使用reduce() + add
我们还可以使用reduce函数来执行该函数同时在列表中执行一对相似数字的加法。
# Python3 code to demonstrate
# to perform element duplication
# using reduce() + add
from operator import add
# initializing list
test_list = [4, 5, 6, 3, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using reduce() + add
# to perform element duplication
res = list(reduce(add, [(i, i) for i in test_list]))
# printing result
print ("The list after element duplication " + str(res))
输出 :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]
方法#3:使用itertools.chain().from_iterable()
from_iterable函数也可用于执行添加副本的任务。它只是制作每个迭代元素的对并依次插入。
# Python3 code to demonstrate
# to perform element duplication
# using itertools.chain.from_iterable()
import itertools
# initializing list
test_list = [4, 5, 6, 3, 9]
# printing original list
print ("The original list is : " + str(test_list))
# using itertools.chain.from_iterable()
# to perform element duplication
res = list(itertools.chain.from_iterable([i, i] for i in test_list))
# printing result
print ("The list after element duplication " + str(res))
输出 :
The original list is : [4, 5, 6, 3, 9]
The list after element duplication [4, 4, 5, 5, 6, 6, 3, 3, 9, 9]