英文:
Python List Comprehension for MmF
问题
如何用列表推导表达这个?
[x for x in unsat_links for i in x.fol if i not in sat_links]
我知道我不应该这样做,但我想重写它以便根据条件更新列表。我尝试使用while循环,但我无法弄清楚。
英文:
How would I express this in list comprehension?
for x in unsat_links:
for i in x.fol:
if i in sat_links:
x.fol.remove(i)
I know I am not supposed to do this, but I want to rewrite it so it updates the list by removing the element based on the condition.
I tried doing a while loop but I could not figure it out.
答案1
得分: 1
# 这是一段代码,主要用于移除不满足条件的链接。
# 以下是一些对该代码的评论:
# “这个列表在这一点上基本上是无用的。你正在进行代码优化。你也可以考虑使用生成器。”
# “在迭代过程中改变了 `x.fol` 的大小,这是不好的,应该避免。”
# “如果你不关心顺序和重复项,最好的方法是使用 `set` 的差集运算。”
((x.fol.remove(i) for i in x.fol if i in sat_links) for x in unsat_links)
英文:
((x.fol.remove(i) for i in x.fol if i in sat_links) for x in unsat_links)
Keep in mind, the list is basically useless at this point. All you are doing is code golfing. You also might as well use generators.
This also changes the size of x.fol
during iteration which is bad and should probably be avoided.
The best way of doing this is with set
subtraction if you do not care about order and duplicates.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论