用python中的列表附加替换打印循环
我想通过算法更改带有 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用理解列表:
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 doout = list(range(container))