Python|将单个值与所有列表项相关联
有时我们遇到一个实用程序,其中我们有一个列表,我们希望将任何一个给定值与它相关联。这可能发生在编程的许多阶段,并且知道它的速记可能很有用。让我们讨论一些可以做到这一点的方法。
方法 #1:使用map()
+ lambda
此任务可以使用 map函数完成,该函数是内置的Python函数,通常用于关联或聚合值。 Lambda函数可以将特定值提供给 map函数以供其执行。
# Python3 code to demonstrate
# associate value in list
# using map() + lambda
# initializing list
test_list = [1, 4, 5, 8, 3, 10]
# initializing value to associate
val = 'geeks'
# printing the original list
print ("The original list is : " + str(test_list))
# printing value
print ("The value to be attached to each value : " + str(val))
# using map() + lambda
# associate value in list
res = list(map(lambda i: (i, val), test_list))
# printing result
print ("The modified attached list is : " + str(res))
The original list is : [1, 4, 5, 8, 3, 10]
The value to be attached to each value : geeks
The modified attached list is : [(1, ‘geeks’), (4, ‘geeks’), (5, ‘geeks’), (8, ‘geeks’), (3, ‘geeks’), (10, ‘geeks’)]
方法#2:使用zip() + itertools.repeat()
zip函数可用于将所需的值附加到序列中的元素,重复函数可用于以更有效的方式将任务扩展到所有列表元素。
# Python3 code to demonstrate
# associate value in list
# using zip() + itertools.repeat()
from itertools import repeat
# initializing list
test_list = [1, 4, 5, 8, 3, 10]
# initializing value to associate
val = 'geeks'
# printing the original list
print ("The original list is : " + str(test_list))
# printing value
print ("The value to be attached to each value : " + str(val))
# using zip() + itertools.repeat()
# associate value in list
res = list(zip(test_list, repeat(val)))
# printing result
print ("The modified attached list is : " + str(res))
The original list is : [1, 4, 5, 8, 3, 10]
The value to be attached to each value : geeks
The modified attached list is : [(1, ‘geeks’), (4, ‘geeks’), (5, ‘geeks’), (8, ‘geeks’), (3, ‘geeks’), (10, ‘geeks’)]