【发布时间】: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
我想通过循环遍历每个列表中的每个字符串并将两个列表用空格分隔来创建一个长字符串:
listA = ["a","b"]
listb = ["1","2","3"]
new_string = "a1 a2 a3 b1 b2 b3"
【问题讨论】:
' '.join(map(''.join, itertools.product(listA, listb)))
标签: python
试试这个:
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
【讨论】:
真的很简单print( ' '.join([ str(i)+str(j) for i in listA for j in listB]))
【讨论】:
' '.join([str(i)+str(j)+' ' for i in listA for j in listB]))
In [14]: ' '.join([' '.join(x + i for i in listb) for x in listA])
Out[14]: 'a1 a2 a3 b1 b2 b3'
【讨论】:
这是一个非常简单的问题解决方案,通常在开始学习 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 中编码。
【讨论】: