具有空列表解释的嵌套列表的总和

时间:2013-10-18 15:32:36

标签: python

我正在完成gensim教程并遇到了一些我不理解的问题。 texts是一个嵌套的字符串列表:

In [37]: texts
Out[37]:
[['human', 'machine', 'interface', 'lab', 'abc', 'computer', 'applications'],
 ['survey', 'user', 'opinion', 'computer', 'system', 'response', 'time'],
 ['eps', 'user', 'interface', 'management', 'system'],
 ['system', 'human', 'system', 'engineering', 'testing', 'eps'],
 ['relation', 'user', 'perceived', 'response', 'time', 'error', 'measurement'],
 ['generation', 'random', 'binary', 'unordered', 'trees'],
 ['intersection', 'graph', 'paths', 'trees'],
 ['graph', 'minors', 'iv', 'widths', 'trees', 'well', 'quasi', 'ordering'],
 ['graph', 'minors', 'survey']]

sum(texts,[])给出:

Out[38]:
['human',
 'machine',
 'interface',
 'lab',
 'abc',
 'computer',
 'applications',
 'survey',
 'user',
 'opinion',
 'computer',

列表继续了几行,但我省略了其余的以节省空间。我有两个问题:

1)为什么sum(texts,[])会产生结果(即展平嵌套列表)?

2)为什么输出显示奇怪 - 每行一个元素?这个输出有什么特别之处(......或者我怀疑它可能是我的iPython表现得很奇怪)。请确认您是否也看到了这一点。

3 个答案:

答案 0 :(得分:6)

这是因为将列表连在一起连接起来。

sum([a, b, c, d, ..., z], start)

相当于

start + a + b + c + d + ... + z

所以

sum([['one', 'two'], ['three', 'four']], [])

相当于

[] + ['one', 'two'] + ['three', 'four']

哪个给你

['one', 'two', 'three', 'four']

请注意,默认情况下,start0,因为默认情况下它适用于数字,因此如果您尝试

sum([['one', 'two'], ['three', 'four']])

那么它会尝试相当于

0 + ['one', 'two'] + ['three', 'four']

它会失败,因为你无法将整数添加到列表中。


每行一件事就是IPython决定输出你的长字符串列表。

答案 1 :(得分:2)

首先,它是以这种方式显示的,因为你正在使用ipython。

其次,考虑如何定义sum。你熟悉函数式编程吗?

如果你自己定义它,你会写出类似的东西:

def sum(lst, start):
    if len(lst) == 1:
        return lst[0] + start
    else:
        return lst[0] + sum(lst[1:], start)

在列表列表上运行此操作相当于说

[['a','b'] + ['c','d'] + []] # for example

导致:

['a','b','c','d']

或换句话说,使列表变平。

答案 2 :(得分:0)

因为你也可以在列表上执行添加(和其他操作),所以你实际上是在一起添加列表来创建一个巨大的列表。

['a'] + ['b'] = ['a','b']