8

我想做类似的事情:

all = [ x for x in t[1] for t in tests ]

测试看起来像:

[ ("foo",[a,b,c]), ("bar",[d,e,f]) ]

所以我想要结果

all = [a,b,c,d,e,f]

我的代码不起作用,Python 说:

UnboundLocalError: local variable 't' referenced before assignment

有什么简单的方法可以做到这一点吗?

4

4 回答 4

17

它应该以相反的方式工作:

all = [x for t in tests for x in t[1]]
于 2009-11-09T10:07:11.167 回答
5

如有疑问,请不要使用列表推导。

在你的 Python shell 中尝试import this并阅读第二行:

Explicit is better than implicit

这种类型的列表推导式的组合会让很多 Python 程序员感到困惑,所以至少添加一个注释来说明您正在删除字符串并展平剩余的列表。

在列表推导式清晰易懂的地方使用列表推导式,尤其是当它们是惯用的时使用它们,即常用的,因为它们是表达某事的最有效或最优雅的方式。例如,这篇 Python Idioms 文章给出了以下示例:

result = [3*d.Count for d in data if d.Count > 4]

它清晰、简单、直接。如果您注意格式,嵌套列表推导式并不算太糟糕,并且可能会添加注释,因为大括号可以帮助读者分解表达式。但在我看来,这个问题所接受的解决方案过于复杂和令人困惑。它超越了界限,使代码对太多人来说不可读。最好将至少一次迭代展开到 for 循环中。

于 2009-11-09T10:26:17.977 回答
2

If all you are doing is adding together some lists, try the sum builtin, using [] as a starting value:

all = sum((t[1] for t in tests), [])
于 2009-11-09T16:57:37.657 回答
1

That looks like a reduce to me. Unfortunately Python does not offer any syntactic sugar for reduce, so we have to use lambda:

reduce(lambda x, y: x+y[1], tests, [])
于 2009-11-09T16:50:47.473 回答