组合字符串并多次打印
假设我有两个列表,我想打印第一个列表的每个元素,然后是第二个列表的每个元素。为了好玩,我还可以在这两个元素之间添加一个单词,例如“和”?
示例:
firstList = (“cats”, “hats”, “rats”)
secondList = (“dogs”, “frogs”, “logs”)
我想要的是什么:
cats and dogs
cats and frogs
cats and logs
hats and dogs
hats and frogs
hats and logs
rats and dogs
etc...
答案 0 :(得分:1)
如果我明白你的意思,这应该很容易。
for item1 in firstlist:
for item2 in secondlist:
print(item1+ " and "+item2)
答案 1 :(得分:1)
您可以将此作为嵌套列表理解
items = ['%s and %s' % (a,b) for b in secondList for a in firstList]
如果您只想打印值,可以插入print
声明
ignore = [print('%s and %s' % (a,b)) for b in secondList for a in firstList]
或者如果您更喜欢format
ignore = [print('{0} and {1}'.format(a,b)) for b in secondList for a in firstList]
答案 2 :(得分:1)
你可以使用两个for
的列表理解:
>>> words = [x + " and " + y for x in firstList for y in secondList]
>>> print(*words, sep="\n")
cats and dogs
cats and frogs
cats and logs
hats and dogs
hats and frogs
hats and logs
rats and dogs
rats and frogs
rats and logs
如果您想枚举列表,可以使用enumerate
,如下所示:
>>> words = ["{}: {} and {}".format(i, x, y) for i, (x, y) in enumerate([(x, y) for x in firstList for y in secondList])]
>>> print(*words)
0: cats and dogs
1: cats and frogs
2: cats and logs
3: hats and dogs
4: hats and frogs
5: hats and logs
6: rats and dogs
7: rats and frogs
8: rats and logs
要使编号从1开始,请将"{}: {} and {}".format(i, x, y)
更改为"{}: {} and {}".format(i + 1, x, y)
。
答案 3 :(得分:1)
除了其他答案之外,另一种方法是使用itertools.product
。
import itertools
firstList = (“cats”, “hats”, “rats”)
secondList = (“dogs”, “frogs”, “logs”)
for item in itertools.product(firstList, secondList):
print(item[0] + " and " + item[1])