Python:将单个元素与列表中的每个元素配对

时间:2015-12-02 18:27:26

标签: python list tuples

例如: myStr = 'z'将与myList = ['a','b','c']配对,以便输出如下:

['z','a']
['z','b']
['z','c']

单线会很棒!

我试着这样做:

print zip([myStr, x] for x in myList)

但输出并不像我想的那样,就像在这里:

[(['z', 'a'],), (['z', 'b'],), (['z', 'c'],)]

4 个答案:

答案 0 :(得分:4)

试试这个:

myList = ['a','b','c']
myStr = 'z'
res = [[myStr, x] for x in myList]

答案 1 :(得分:1)

使用zip

>>> zip(myStr*3,myList)
[('z', 'a'), ('z', 'b'), ('z', 'c')]

答案 2 :(得分:0)

Itertools - izip-longest

>>>from itertools import izip_longest
>>>[list(i) for i  in list(izip_longest(['z'],['a','b','c'],fillvalue ='z'))]
>>>[['z', 'a'], ['z', 'b'], ['z', 'c']]

答案 3 :(得分:0)

from itertools import izip_longest
list(izip_longest([], ['a','b','c'], fillvalue='z'))