在Python中将单个值与所有列表项关联


我们可能需要将给定的值与列表中的每个元素关联。例如,我们有星期几的名字,并且想要在每个名字后面添加“日”作为后缀。此类场景可以通过以下方式处理。

使用itertools.repeat

我们可以使用itertools模块中的repeat方法,以便在使用zip函数将相同的值与给定列表中的值配对时,该值会被重复使用。

示例

 在线演示

from itertools import repeat

listA = ['Sun','Mon','Tues']
val = 'day'
print ("The Given list : ",listA)
print ("Value to be attached : ",val)
# With zip() and itertools.repeat()
res = list(zip(listA, repeat(val)))
print ("List with associated vlaues:\n" ,res)

输出

运行上述代码将得到以下结果:

The Given list : ['Sun', 'Mon', 'Tues']
Value to be attached : day
List with associated vlaues:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]

使用lambda和map

lambda方法对列表元素进行迭代并开始配对它们。map函数确保列表中的所有元素都包含在将列表元素与给定值配对的过程中。

示例

 在线演示

listA = ['Sun','Mon','Tues']
val = 'day'
print ("The Given list : ",listA)
print ("Value to be attached : ",val)
# With map and lambda
res = list(map(lambda i: (i, val), listA))
print ("List with associated vlaues:\n" ,res)

输出

运行上述代码将得到以下结果:

The Given list : ['Sun', 'Mon', 'Tues']
Value to be attached : day
List with associated vlaues:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]

更新于:2020年7月10日

287 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.