在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 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告