Python 组合字符串并打印多次

Python Combining strings and printing multiple times

组合字符串并多次打印

假设我有两个列表,我想打印第一个列表的每个元素,然后打印第二个列表的每个元素。为了好玩,我能不能在这两个元素之间加一个词,比如“and”?

示例:

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...

如果我明白你的意思,这应该很容易。

for item1 in firstlist:
    for item2 in secondlist:
        print(item1+ " and "+item2)

您可以将其作为嵌套列表推导来执行

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]

您可以使用包含两个 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)

除了其他答案之外,另一种方法是 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])