Python中的列表推导式用于MmF。

huangapple go评论52阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月13日 00:26:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定