Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 2 lists :

x = ['a','b','c']
y = ['d','e','f']

I need a single list of lists :

z = [['a','d'],['b','e'],['c','f']]

What I tried :

# Concatenate x and y with a space
w = []
for i in range(len(x)):
    w.append(x[i]+" "+y[i])

# Split each concatenated element into a sublist
z = []
for i in range(len(w)):
    z.append(w[i].split())

Is there a way to do this directly without using 2 for loops ? (I am very new to Python)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use zip (itertools.izip if the lists are large):

>>> x = ['a','b','c']
>>> y = ['d','e','f']
>>> zip(x, y)
[('a', 'd'), ('b', 'e'), ('c', 'f')]
>>> map(list, zip(x, y))  # If you need lists instead of tuples
[['a', 'd'], ['b', 'e'], ['c', 'f']]
>>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...