【问题标题】:Combining lists in python在python中组合列表
【发布时间】:2014-09-11 05:51:07
【问题描述】:

我正在尝试合并 2 个列表并希望形成组合。

a = ['ibm','dell']
b = ['strength','weekness']

我想形成像['ibm strength','ibm weekness','dell strength','dell weakness'] 这样的组合。

我尝试使用 zip 或连接列表。我也使用了 itertools 但它没有给我想要的输出。请帮忙。

a = ['ibm','dell']
b = ['strength','weekness']
c = a + b
itertools.combinations(c,2)
for a in a:
    for b in b:
        print a +b

【问题讨论】:

    标签: python list python-2.7 combinations


    【解决方案1】:

    您正在寻找product()。试试这个:

    import itertools
    
    a = ['ibm', 'dell']
    b = ['strength', 'weakness']
    
    [' '.join(x) for x in itertools.product(a, b)]
    => ['ibm strength', 'ibm weakness', 'dell strength', 'dell weakness']
    

    要遍历结果,不要忘记itertools.product() 返回一个迭代器,它只能被使用一次。如果您以后需要它,请将其转换为列表(就像我上面所做的那样,使用列表推导式)并将结果存储在变量中以备将来使用。例如:

    lst = list(itertools.product(a, b))
    for a, b in lst:
        print a, b
    

    【讨论】:

    • 感谢奥斯卡的及时回复。您还可以解释为什么当我遍历项目并加入它们时列表项目开始消失。在我使用循环之后,列表变空了
    • 这种方式太棒了 Óscar! ;) 不错!
    • @RaghavShaligram 这不会发生在我身上……请发布导致问题的代码。此外,您应该将列表保存在一个变量中,以备将来使用
    • @ÓscarLópez 我刚刚更新了代码并使用了嵌套循环。列表项开始消失..
    • @RaghavShaligram 您没有在我的答案中使用代码……无论如何,请参阅我的更新。请记住,itertools 中的函数返回 iterators(不是列表),它只能被遍历一次。如果您以后需要使用它们,请将它们转换为列表。而且您必须将结果保存在变量中,仅仅调用函数不会做任何事情
    【解决方案2】:

    对于Cartesian product,您需要itertools.product() 而不是组合。

    嵌套的 for 循环也可以工作:

    for x in a:
        for y in b:
            c = a + b
            print(c)
    

    【讨论】:

      猜你喜欢
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2010-12-02
      • 1970-01-01
      相关资源
      最近更新 更多