我有一个人的“兴趣”列表,看起来像这样:
[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或其他东西,但这似乎是一个很大的痛苦设置,即使它将使分析更容易一旦我这样做了。
发布于 2015-04-01 04:51:48
您可以使用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]]https://stackoverflow.com/questions/29378204
复制相似问题