多个字符串排序列表

2024-10-01 22:38:30 发布

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

我有一张一个人的“兴趣”清单,看起来像:

[u'technology and computing', u'software', u'shareware and freeware']
[u'art and entertainment', u'shows and events', u'festival']
[u'art and entertainment', u'shows and events', u'circus']
[u'technology and computing', u'computer certification']
[u'news']
[u'religion and spirituality', u'islam']

这些是NLP API输出的分类法,我试图进行进一步的分析,根据item[0]=='art and entertainment'出现的频率,以及某人感兴趣的特定艺术和娱乐类型(例如if item[0]=='art and entertainment': return item[:-1]),得出一些更高层次的结论

不管怎样,我可以在一个好的方法上得到一些指导。我的第一个想法是计算列表中某个项目的max(len())(在我的例子5中),然后

for item in list: 
    append((max(len()) - len(item))*'null,')

为了确保它们都有相同数量的“列”,然后将其全部转换为一个命名元组并对其进行多重排序。似乎是个烦人的过程。有没有一个更简单的方法来处理这个问题

我曾经考虑过使用NLTK之类的东西,但这似乎只是一个很大的痛苦设置,即使它会使分析更容易,一旦我这样做了


Tags: and方法lensoftwareeventsitemmaxshows
1条回答
网友
1楼 · 发布于 2024-10-01 22:38:30

您可以使用itertools.izip_longet压缩列表,这样您的列表将包含主列表的列,缺少的元素已替换为None

>>> from itertools import izip_longest
>>> a=[[u'technology and computing', u'software', u'shareware and freeware'],
... [u'art and entertainment', u'shows and events', u'festival'],
... [u'art and entertainment', u'shows and events', u'circus'],
... [u'technology and computing', u'computer certification'],
... [u'news'],
... [u'religion and spirituality', u'islam']]

>>> list(izip_longest(*a))
[(u'technology and computing', u'art and entertainment', u'art and entertainment', u'technology and computing', u'news', u'religion and spirituality'), (u'software', u'shows and events', u'shows and events', u'computer certification', None, u'islam'), (u'shareware and freeware', u'festival', u'circus', None, None, None)]

然后你可以对你的列做任何你想做的操作

但如果您只想将None添加到不完整列表中,您可以使用itertools.repeat

>>> max_len=max(map(len,a))
>>> from itertools import repeat
>>> [i+list(repeat(None,max_len-len(i))) for i in a]
[[u'technology and computing', u'software', u'shareware and freeware'], [u'art and entertainment', u'shows and events', u'festival'], [u'art and entertainment', u'shows and events', u'circus'], [u'technology and computing', u'computer certification', None], [u'news', None, None], [u'religion and spirituality', u'islam', None]]

相关问题 更多 >

    热门问题