如何在python中为列表中的每个字符串生成子列表?

2024-10-02 18:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有以下列表:

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字符串成为一个子列表?在


Tags: community列表bodysystemorganizationadministrationorganisationformation
3条回答

我找到了!感谢上面的Meow先生给了我灵感。

upuplist1 = []
for i in newlist1:
    upuplist1.append([i])

print upuplist1

以下是我期望的输出:

^{pr2}$

像这样?

uplist1 = []
for i in syn1:
    uplist1.append([i])

编辑:

与列表理解等效:

^{pr2}$

在创建newlist1时,需要在列表理解中将[]添加到val中,以便将string放入list中,例如:

newlist1 = [[val] for sublist in syn1 for val in sublist]

相关问题 更多 >