组合和循环列表python

时间:2015-05-10 08:40:06

标签: python

first_name = ["Johnny", "Joseph", "Mary"]
third_name = ["Mendez", "Nash", "Johanson"]
second_name = ["John", "Allen", "Ann"]


for i in first_name:
    for x in second_name:
        for y in third_name:
            names = i + x + y

我们如何进行输出:

[Johnny John Mendez, Joseph Allen Nash, Mary Ann Johanson]

因为当我遍历所有列表时,我得到了混乱的名字。我们如何制作名称的顺序。 first_name second_name third_name

3 个答案:

答案 0 :(得分:5)

使用zip()

for first, second, third in zip(first_name, second_name, third_name):
    print "{} {} {}".format(first, second, third)

zip函数同时遍历三个列表,并在每次迭代时从每个列表中获取相应的元素。

答案 1 :(得分:2)

使用zipmap

map(" ".join, zip(first_names, second_names, third_names))

REPL中的示例:

>>> map(" ".join, zip(["A", "B", "C"], ["a", "b", "c"], ["1", "2", "3"]))
['A a 1', 'B b 2', 'C c 3']

然后你可以创建一个你可能在其他地方使用的函数:

def make_names(first_names, second_names, third_names):
    return map(" ".join, zip(first_names, second_names, third_names))

或者甚至更一般地,不是硬编码正好三个名称部分:

def make_names(*args):
    return map(" ".join, zip(*args))

REPL示例:

>>> make_names(["a"])
['a']
>>> make_names(["a"], ["b"])
['a b']
>>> make_names(["a"], ["b"], ["c"], ["d"])
['a b c d']
>>> make_names(["Johnny", "Joseph", "Mary"], ["Mendez", "Nash", "Johanson"], ["John", "Allen", "Ann"])
['Johnny Mendez John', 'Joseph Nash Allen', 'Mary Johanson Ann']

答案 2 :(得分:0)

如果您有不等大小的列表

,这将有效
In [18]: import itertools
In [19]: [x for x in itertools.chain.from_iterable(itertools.izip_longest(first_name,second_name,third_name)) if x]
Out[19]:["Johnny","John Mendez","Joseph", "Allen", "Nash", "Mary", "Ann", "Johanson"]