简体   繁体   English

如何用数字和字符串连接 python 中的两个列表?

[英]how to concatenate two lists in python with numbers and strings?

i want to merge two lists together, but not one after the other我想将两个列表合并在一起,但不是一个接一个地合并

list1=[1,2,3,4]
list2=[a,b,c,d,e,f]

and the output should be输出应该是

list3=[1a,2b,3c,4d,e,f]

Use itertools.zip_longest to iterate over lists of uneven length, and provide a default value ( fillvalue ) for the missing elements.使用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)

Output输出

['1a', '2b', '3c', '4d', 'e', 'f']

The expression f"{a}{b}" is known as an f-string and is used to format strings.表达式f"{a}{b}"被称为f 字符串,用于格式化字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM