【问题标题】:How to each item in list with all values of another list in Python [duplicate]如何将列表中的每个项目与Python中另一个列表的所有值一起使用[重复]
【发布时间】:2012-10-23 09:37:20
【问题描述】:

可能重复:
All combinations of a list of lists

我一直在尝试使用 python 将两个字符串列表添加在一起,但我无法让它与我尝试过的不同 for 循环安排一起工作。我有两个列表,我想从另外两个列表中创建第三个列表,以便列表 1 中的 index[0] 依次添加列表 2 中的所有索引(每个都是新列表中的单独条目list),然后对于 list1 中的 index[1] 也是如此,依此类推..

snippets1 = ["aka", "btb", "wktl"]
snippets2 = ["tltd", "rth", "pef"]

resultlist = ["akatltd", "akarth", "akapef", "btbtltd", "btbrth", "btbpef", "wktltltd", "wktlrth", "wktlpef"]

我知道答案很简单,但无论我做什么,我都会得到一些根本不起作用的东西,或者它会将 sn-ps1[0] 添加到 sn-ps2[0]、sn-ps1[1]到 sn-ps2[1] 等等。请帮忙!

【问题讨论】:

    标签: python


    【解决方案1】:
    import itertools
    
    snippets1 = ["aka", "btb", "wktl"]
    snippets2 = ["tltd", "rth", "pef"]
    
    resultlist = [''.join(pair) for pair in itertools.product(snippets1, snippets2)]
    

    【讨论】:

      【解决方案2】:

      你可以这样试试

      resultlist=[]
      for i in snipppets1:
       for j in snippets2:
        resultlist.append(i+j)
      print resultlist
      

      【讨论】:

      • 谢谢。这是我最初试图达到的目标,但我一直在搞砸
      【解决方案3】:

      为了完整起见,我想我应该指出一个不使用 itertools 的衬垫(但应该首选带有 product 的 itertools 方法):

      [i+j for i in snippets1 for j in snippets2]
      # ['akatltd', 'akarth', 'akapef', 'btbtltd', 'btbrth', 'btbpef', 'wktltltd', 'wktlrth', 'wktlpef']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-13
        • 2020-01-01
        • 2021-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        相关资源
        最近更新 更多