【问题标题】:Create one long string from two lists of strings [duplicate]从两个字符串列表创建一个长字符串[重复]
【发布时间】:2017-08-04 16:32:29
【问题描述】:

我想通过循环遍历每个列表中的每个字符串并将两个列表用空格分隔来创建一个长字符串:

listA = ["a","b"]
listb = ["1","2","3"]

new_string = "a1 a2 a3 b1 b2 b3"

【问题讨论】:

  • ' '.join(map(''.join, itertools.product(listA, listb)))

标签: python


【解决方案1】:

试试这个:

from itertools import product

listA = ["a","b"]
listb = ["1","2","3"]
new_string = " ".join(a + b for a, b in product(listA, listb))
print(new_string)
>>> a1 a2 a3 b1 b2 b3

【讨论】:

    【解决方案2】:

    真的很简单
    print( ' '.join([ str(i)+str(j) for i in listA for j in listB]))

    【讨论】:

    • @whackamadoodle 你能指出错误具体是什么吗?
    • 对不起,我误解了这个问题,我的不起作用。我刚删了
    • 方法很棒,但结果缺少退格。 ' '.join([str(i)+str(j)+' ' for i in listA for j in listB]))
    【解决方案3】:
    In [14]: ' '.join([' '.join(x + i for i in listb) for x in listA])
    Out[14]: 'a1 a2 a3 b1 b2 b3'
    

    【讨论】:

      【解决方案4】:

      这是一个非常简单的问题解决方案,通常在开始学习 for 循环时教授(至少对我来说是这样):

      listA = ["a","b"]
      listb = ["1","2","3"]
      new_string = ""
      
      for i in listA:
          for j in listb:
              #adding a space at the end of the concatenation 
              new_string = new_string+i+j+" "
      
      
      print(new_string)
      

      在 python 3 中编码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-11
        • 2012-01-11
        • 2023-03-21
        • 2011-07-24
        • 2013-07-24
        • 1970-01-01
        • 1970-01-01
        • 2017-02-13
        相关资源
        最近更新 更多