如何将此代码转换为af字符串?

Dam*_*mon 3 python python-3.x

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
Run Code Online (Sandbox Code Playgroud)

所以我试图删除那些%s%s而不是字符串格式.有人能够表达如何做到这一点.谢谢

nos*_*klo 6

>>> colors = ['black', 'white']
>>> sizes = ['S', 'M', 'L']
>>> for c in colors:
...    for s in sizes:
...        print(f'{c} {s}')
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用itertools.product:

>>> for c, s in itertools.product(colors, sizes):
...     print(f'{c} {s}')   
Run Code Online (Sandbox Code Playgroud)


Wil*_*sem 6

您可以用大括号({...})编写变量名称:

for tshirt in (f'{c} {s}' for c in colors for s in sizes):
    print(tshirt)
Run Code Online (Sandbox Code Playgroud)

虽然在这种情况下使用生成器进行for循环有点奇怪:你可以展开成(两个)嵌套for循环,就像在@nosklo的答案中一样(尽管这当然不会改变文字字符串插值的用法)[PEP-498].