开发者

appending a string to another string

开发者 https://www.devze.com 2023-01-28 18:25 出处:网络
I have 2 lists : list1 contains \"T\" \"F\" \"T\" \"T\" list2 con开发者_StackOverflow中文版tains \"a\" \"b\" \"c\" \"d\"

I have 2 lists :

list1 contains "T" "F" "T" "T"

list2 con开发者_StackOverflow中文版tains "a" "b" "c" "d"

I want to create a third list such that I append element1 in list1 to element1 in list2.

So list3 would be the following: "Ta" "Fb" "Tc" "Td"

How can i do that?


Use zip: [x + y for x, y in zip(list1, list2)].


zip, as others have suggested, is good. izip, I would suggest, is better for longer lists.

>>> from itertools import izip
>>> list3 = [x+y for x,y in izip(list1, list2)]
>>> list3
['Ta', 'Fb', 'Tc', 'Td']

See also the documentation on list comprehensions, they're an essential tool in Python programming.


Your lists

>>> t = ["T", "F", "T", "T"]
>>> t1 = ["a", "b", "c", "d"]

Group them using zip function:

>>> t2 = zip(t, t1)
>>> t2
[('T', 'a'), ('F', 'b'), ('T', 'c'), ('T', 'd')]

You could now manipulate the list for desired result:

>>> ["".join(x) for x in t2]
['Ta', 'Fb', 'Tc', 'Td']
>>> 
0

精彩评论

暂无评论...
验证码 换一张
取 消