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

时间:2018-07-09 20:15:51

标签: 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

因此,我尝试删除那些%s%s,而是采用f字符串格式。有人可以表现出如何做到这一点吗?谢谢

2 个答案:

答案 0 :(得分:6)

>>> 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}')   

答案 1 :(得分:6)

您可以将变量名写在花括号{...})中:

for tshirt in (f'{c} {s}' for c in colors for s in sizes):
    print(tshirt)

尽管在这种情况下使用生成器进行for循环有点奇怪:您可以将其展开成(两个)嵌套的for循环,例如@nosklo的回答(尽管这当然不会改变literal string interpolation [PEP-498]的用法。