colors = ['black', 'white']
sizes = ['S', 'M', 'L']
for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):
print(tshirt)
black S
black M
black L
white S
white M
white L
所以我试图删除那些 %s %s ,而是使用 af 字符串格式。有人可以很好地展示这是如何完成的。谢谢
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
for tshirt in ('%s %s' % (c, s) for c in colors for s in sizes):
print(tshirt)
black S
black M
black L
white S
white M
white L
所以我试图删除那些 %s %s ,而是使用 af 字符串格式。有人可以很好地展示这是如何完成的。谢谢
>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> for c in colors:
... for s in sizes:
... print(f'{c} {s}')
另一种方法是使用itertools.product
:
>>> for c, s in itertools.product(colors, sizes):
... print(f'{c} {s}')
您可以将变量名写在大括号( {...}
) 中:
for tshirt in (f'{c} {s}' for c in colors for s in sizes):
print(tshirt)
尽管在这种情况下使用生成器进行循环有点奇怪for
:您可以将其展开为(两个)嵌套for
循环,就像在@nosklo 的回答中一样(尽管这当然不会改变文字字符串插值的使用) [PEP-498]。