在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')]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP