例如,我有以下列表:
word1 = ['organization', 'community']
我有一个函数可以从列表中的单词中获取同义词:
^{pr2}$输出如下:
[[u'organization', u'organisation', u'arrangement', u'system', u'administration', u'governance', u'governing body', u'establishment', u'brass', u'constitution', u'formation'], [u'community', u'community of interests', u'residential district', u'residential area', u'biotic community']]
^上面的输出显示'organization'
和'community'
的每个语法集都在一个列表中进行子列表。然后我降低列表级别:
newlist1 = [val for sublist in syn1 for val in sublist]
输出如下:
[u'organization', u'organisation', u'arrangement', u'system', u'administration', u'governance', u'governing body', u'establishment', u'brass', u'constitution', u'formation', u'community', u'community of interests', u'residential district', u'residential area', u'biotic community']
^现在所有的语法集都保持不变,没有子列表。我现在要做的是使newlist1
中的所有synsets都能相互重复列出。我希望输出如下:
[[u'organization'], [u'organisation'], [u'arrangement'], [u'system'], [u'administration'], [u'governance'], [u'governing body'], [u'establishment'], [u'brass'], [u'constitution'], [u'formation'], [u'community'], [u'community of interests'], [u'residential district'], [u'residential area'], [u'biotic community']]
我在尝试这个代码:
uplist1 = [[] for x in syn1]
uplist1.extend(syn1)
print uplist1
但结果并不是我所期望的:
[[], [], [u'organization', u'organisation', u'arrangement', u'system', u'administration', u'governance', u'governing body', u'establishment', u'brass', u'constitution', u'formation'], [u'community', u'community of interests', u'residential district', u'residential area', u'biotic community']]
它显示了'organization'
和'community'
的两个空列表和两个synset列表
如何使每个synsets字符串成为一个子列表?在
我找到了!感谢上面的
Meow
先生给了我灵感。以下是我期望的输出:
^{pr2}$像这样?
编辑:
与列表理解等效:
^{pr2}$在创建
newlist1
时,需要在列表理解中将[]
添加到val
中,以便将string
放入list
中,例如:相关问题 更多 >
编程相关推荐