Python|在列表中多次添加相似的值
在列表中添加单个值非常通用且容易。但是要多次添加该值,通常会使用循环来执行此任务。使用更短的技巧来执行此操作会很方便。让我们讨论一些可以做到这一点的方法。
方法 #1:使用 *运算符
我们可以使用 *运算符来乘以特定值的出现,因此可以用于在一行中执行多次添加值并使其可读的任务。
# Python3 code to demonstrate
# to add multiple similar values
# using * operator
# using * operator to add multiple values
# adds 3, 50 times.
res = [3] * 50
# printing result
print ("The filtered list is : " + str(res))
输出 :
The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
方法#2:使用extend()
+ 列表推导
扩展函数用于执行列表追加和列表理解部分负责执行重复元素所需次数的任务。
# Python3 code to demonstrate
# to add multiple similar values
# using extend() + list comprehension
# using extend() + list comprehension to add multiple values
# adds 3, 50 times.
res = []
res.extend([3 for i in range(50)])
# printing result
print ("The filtered list is : " + str(res))
输出 :
The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
方法 #3:使用extend() + itertools.repeat()
这与上述方法类似, extend()
的任务类似,但repeat()
执行第 N 次迭代执行的任务列表推导。所需的次数。
# Python3 code to demonstrate
# to add multiple similar values
# using extend() + itertools.repeat()
from itertools import repeat
# using extend() + itertools.repeat() to add multiple values
# adds 3, 50 times.
res = []
res.extend(repeat(3, 50))
# printing result
print ("The filtered list is : " + str(res))
输出 :
The filtered list is : [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]