用python中的列表附加替换打印循环

发布于 2025-01-20 07:52:01 字数 839 浏览 2 评论 0原文

我想通过算法更改带有 print 语句的循环以列出附加内容,以便我可以返回它们。嵌套循环的数量没有限制,if 语句的数量也没有限制。例如,我有代码块:

for i,elem in enumerate(container):
    for j in elem:
        if j!=i:
           print(j)
    print(i)

我想通过算法将其更改为

out = []
for i,elem in enumerate(container):
    for j in elem:
        if j!=i:
           out.append(str(j))
    out.append(str(i))

是否有一个库可以执行此操作?我已经看到了 refactor绳子 但他们似乎没有完成这项工作。

我知道有 ast 模块,但我不想自己制作从头开始。

I want to algorithmically change loops with print statements to list appends so that I can return them. There is no limit to the number of nested loops nor if there are if statements. For example, I have the code block:

for i,elem in enumerate(container):
    for j in elem:
        if j!=i:
           print(j)
    print(i)

And I want to algorithmically change it to

out = []
for i,elem in enumerate(container):
    for j in elem:
        if j!=i:
           out.append(str(j))
    out.append(str(i))

Is there a library that could potentially do this? I have seen both refactor and rope but they do not seem to do the job.

I know there is the ast module but I would prefer not to make my own from scratch.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷弦 2025-01-27 07:52:01

您可以使用理解列表:

out_2 = [str(j) for elem in container for j in elem if j!=i]

如果您想保留 out 列表,只需执行 out = list(range(container))

You can use comprehension lists:

out_2 = [str(j) for elem in container for j in elem if j!=i]

And if you want to keep out list, simply do out = list(range(container))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文