带空列表说明的嵌套列表之和

2024-05-14 17:40:02 发布

您现在位置: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,[])给出:

^{pr2}$

这个列表又多了几行,但为了节省空间,我省略了其余的行。我有两个问题:

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

2)为什么输出显示奇怪-每行一个元素?这个输出有什么特别的地方吗(…或者我怀疑可能是我的iPython行为异常)。请确认您是否也看到了这个。


Tags: 列表timeresponseepssystemtreesinterfacesurvey
3条回答

这是因为将列表添加到一起会将它们连接起来。在

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

相当于

^{pr2}$

所以

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

相当于

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

这给了你

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

注意start,默认情况下是0,因为默认情况下它与数字一起工作,所以如果您要尝试

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

然后它会尝试相当于

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

它会失败,因为你不能把整数加到列表中。在


每行一个的问题就是IPython是如何决定输出一长串字符串的。在

首先,它是这样显示的,因为您使用的是ipython。在

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

如果你自己去定义它,你会写下这样的话:

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

在一个列表中运行这个相当于说

^{pr2}$

结果是:

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

或者,换言之,就是把名单弄平。在

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

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

相关问题 更多 >

    热门问题