简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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