[英]how to concatenate two lists in python with numbers and strings?
我想將兩個列表合並在一起,但不是一個接一個地合並
list1=[1,2,3,4]
list2=[a,b,c,d,e,f]
輸出應該是
list3=[1a,2b,3c,4d,e,f]
使用itertools.zip_longest
迭代長度不均勻的列表,並為缺失的元素提供默認值 ( fillvalue
)。
from itertools import zip_longest
list1 = [1, 2, 3, 4]
list2 = ["a", "b", "c", "d", "e", "f"]
res = [f"{a}{b}" for a, b in zip_longest(list1, list2, fillvalue="")]
print(res)
輸出
['1a', '2b', '3c', '4d', 'e', 'f']
表達式f"{a}{b}"
被稱為f 字符串,用於格式化字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.