【问题标题】:Join list2 for every string in list1为 list1 中的每个字符串加入 list2
【发布时间】:2020-08-21 21:27:54
【问题描述】:

我已经设置了两个这样的列表

List1 = ["A", "B", "C"]
List2 = ["1", "2", "3", "4", "5"]

我想为 list1 中的每个字符串加入 list2 的每个字符串,例如,我希望上述列表的最终结果在文本文件中看起来像这样:

A:1
A:2
A:3
A:4
A:5
B:1
B:2
B:3
B:4
B:5
C:1
C:2
C:3
C:4
C:5

这可以实现吗?

【问题讨论】:

  • 是的,您似乎想要其中的笛卡尔product

标签: python string list join output


【解决方案1】:

我想这会有所帮助...

List1 = ["A", "B", "C"]
List2 = ["1", "2", "3", "4", "5"]
file1 = open("MyFile.txt","w") 
for i in List1:
    for j in List2:
        file1.write(i+":"+j+"\n")

【讨论】:

    【解决方案2】:

    您可以使用itertools 库中的product 函数:

    from itertools import product
    
    list1 = ["A", "B", "C"]
    list2 = ["1", "2", "3", "4", "5"]
    with open("text_file.txt", "w") as text_file:
        for element_from_list1, element_from_list2 in product(list1, list2):
            text_file.write((element_from_list1 + ":" + element_from_list2 + "\n"))
    

    会导致

    A:1 A:2 A:3 A:4 A:5 B:1 B:2 B:3 B:4 B:5 C:1 C:2 C:3 C:4 C:5

    在文本文件中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2021-04-13
      • 2021-04-27
      • 2019-10-04
      • 2021-09-10
      相关资源
      最近更新 更多