【问题标题】:Is there a way to use the for loop within a print statement?有没有办法在 print 语句中使用 for 循环?
【发布时间】:2021-06-29 06:48:04
【问题描述】:

我是初学者,请多多包涵

我有以下代码:

shapes = ['rect', 'rect', 'circle']
coords = ["34,44,210", "290,333,250", "337,300,44"]

for shape in shapes:
    for coord in coords:
        print(shape)
        print(coords)

我很清楚这会多次打印出来,但我无法找到避免它的方法。
我认为更好的方法是在 print 语句中一个接一个地使用它,如下所示:

print(shape for shape in shapes)
print(coord for coord in coords)

但这不起作用,只能打印

<generator object <genexpr> at 0x00000282B2C69510>
<generator object <genexpr> at 0x00000282B2C69510>

我找不到在 print 语句中打印 for 循环的指南。
我正在使用它来打印如下内容:

id='rect' id2='34,44,210'
id='rect' id2='290,333,250'
id='circle' id2='337,300,44'

有办法吗?提前致谢。

编辑:我希望能够打印那个确切的东西。

【问题讨论】:

  • 您的预期输出是什么?只打印一次列表的内容?
  • 作为中间步骤,你可以试试print([shape for shape in shapes])。这与您的第一个示例并不完全相同,但可以帮助您更深入地理解 Syed Ahmad 的答案。

标签: python-3.x for-loop


【解决方案1】:

使用生成器表达式已经朝着正确的方向发展。但是,必须是unpacked in the call 才能将项目从生成器中取出到print:

print(*(shape for shape in shapes))

在这种情况下这有点没用,因为生成器没有做任何有用的事情——print(*shapes) 在这里也可以工作。

作为一个更有用的例子,如果你想打印所有形状和坐标的组合,可以使用两个序列的生成器:

shapes = ['rect', 'rect', 'circle']
coords = ["34,44,210", "290,333,250", "337,300,44"]
print(*((shape, coord) for shape in shapes for coord in coords))

Python 附带了已经实现常见迭代模式的各种实用程序。例如,可以通过itertools.product(shapes, coords)创建两个列表的组合。

对于此类数据,您可能需要的是两个可迭代对象的pairwise 折叠。这是一个常见的用例,因此 Python 有一个始终可用的助手:the builtin function zip。

>>> shapes = ['rect', 'rect', 'circle']
>>> coords = ["34,44,210", "290,333,250", "337,300,44"]
>>> # unpack pairs directly
>>> print(*zip(shapes, coords))
('rect', '34,44,210') ('rect', '290,333,250') ('circle', '337,300,44')
>>> #       v ----     format each pair     ---- v
>>> print(*(f"{shape}={coord}" for shape, coord in zip(shapes, coords)))
rect=34,44,210 rect=290,333,250 circle=337,300,44
>>> #       v ----     format each pair     ---- v                     v separate by newline
>>> print(*(f"{shape}={coord}" for shape, coord in zip(shapes, coords)), sep="\n")
rect=34,44,210
rect=290,333,250
circle=337,300,44

请记住,使用常规 for 循环并没有错。如果要在单个换行符分隔的打印解压缩格式化压缩对表达式和多个语句之间进行选择,请使用更具可读性的选项。

for shape, coord in zip(shapes, coords):
    print(shape, '=', coord, sep='')

【讨论】:

  • 两个迭代的成对折叠效果很好,但是它们被括在括号中,我想用它来打印出类似 `` id='rect' id2=' 34,44,210' ``` 其他两个以此类推
  • @RedFox 我已经用字符串格式扩展了示例以获得key=value 类似的输出。希望对您有所帮助。
【解决方案2】:
    print('The shapes are:', '\n'.join([shape for shape in shapes]))
    The lists are: 'rect'
    'rect'
    'circle'

【讨论】:

  • 请参阅此线程以供参考:- link
  • shapes 的内容已经是字符串。无需再次将它们转换为字符串。
  • 您也不需要在join() 中创建列表。 '\n'.join(shape for shape in shapes) 会做
  • 但这会将其放入列表中,我只想将它们打印出来而不放入列表中
  • 我试过了,但对我来说它没有把你的形状放在列表中
【解决方案3】:

你在这里使用的语法:

print(shape for shape in shapes)

是合法的,但它是一个生成器推导,类似于 list comp 但返回一个生成器对象。

但是,由于您想要的输出是字符串,您可以将它们与换行符转义对 \n 连接起来并打印整个字符串一次:

print("\n".join((i for i in shapes)))

注意 str 转换是多余的,因为元素已经是字符串。

【讨论】:

    猜你喜欢
    • 2019-11-05
    • 2020-01-06
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多