在 Python 中将单个值与所有列表项关联
pythonserver side programmingprogramming更新于 2025/7/31 15:08:17
我们可能需要将给定值与列表的每个元素关联起来。例如 − 有日期的名称,我们想在其中附加单词 day 作为后缀。这种情况可以通过以下方式处理。
使用 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)
# 使用 zip() 和 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')]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

