我刚开始使用Python,遇到了以下问题:
假设我有以下列表:
list = [["Word1","Word2","Word2","Word4566"],["Word2", "Word3", "Word4"], ...]我想得到的结果(矩阵)应该如下所示:

所显示的列和行都显示单词(无论哪个列表)。
我想要的是一个计算每个列表中单词外观的程序(按列表)。
图片是第一个列表之后的结果。
有什么简单的方法可以实现像这样或类似的事情吗?
编辑:基本上,我想要一个列表/矩阵,告诉我当单词1也出现在列表中时,单词2-4566出现了多少次,以此类推。
因此,我会得到一个列表,每一个字,显示所有其他4555字的绝对频率与这个词的关系。
因此,我需要一个算法来迭代所有这些单词列表并构建结果列表。
发布于 2016-12-23 14:03:34
我想出了正确的答案来回答我自己的问题:
list = [["Word1","Word2","Word2"],["Word2", "Word3", "Word4"],["Word2","Word3"]]
#Names of all dicts
all_words = sorted(set([w for sublist in list for w in sublist]))
#Creating the dicts
dicts = []
for i in all_words:
dicts.append([i, dict.fromkeys([w for w in all_words if w != i],0)])
#Updating the dicts
for l in list:
for word in sorted(set(l)):
tmpL = [w for w in l if w != word]
ind = ([w[0] for w in dicts].index(word))
for w in dicts[ind][1]:
dicts[ind][1][w] += l.count(w)
print dicts获取结果:
'Word1',{'Word4':0,'Word3':0,'Word2':2},'Word2',{'Word4':1,'Word1':1,'Word3':2},'Word3',{'Word4':1,'Word1':0,'Word2':2},'Word4',{'Word1':0,'Word3':1,'Word2':1}]
发布于 2016-12-23 13:06:33
据我所知,您希望创建一个矩阵,该矩阵显示每对单词的两个单词位于一起的列表数。
首先,我们应该修复一套独特的词语:
lst = [["Word1","Word2","Word2","Word4566"],["Word2", "Word3", "Word4"], ...] # list is a reserved word in python, don't use it as a name of variables
words = set()
for sublst in lst:
words |= set(sublst)
words = list(words)其次,我们应该定义一个含有零的矩阵:
result = [[0] * len(words)] * len(words) # zeros matrix N x N最后,我们通过给定的列表填充矩阵:
for sublst in lst:
sublst = list(set(sublst)) # selecting unique words only
for i in xrange(len(sublst)):
for j in xrange(i + 1, len(sublst)):
index1 = words.index(sublst[i])
index2 = words.index(sublst[j])
result[index1][index2] += 1
result[index2][index1] += 1
print result发布于 2016-12-23 12:20:50
我觉得很难理解你到底想要什么,但我会尝试做一些假设:
如果这些假设是正确的,那么该表就不符合您提供的列表。如果我的假设是错误的,那么我仍然相信我的解决方案可能会给你灵感,或者给你一些如何正确解决它的想法。最后,我不认为我的解决方案是最优的速度或类似。
布斯!!我使用python的内置字典,如果您打算用成千上万的单词填充它们,它们可能会变得非常慢!!看看:https://docs.python.org/2/tutorial/datastructures.html#dictionaries
frq_dict = {} # num of appearances / frequency
uqe_dict = {} # unique
for list_b in list_A:
temp_dict = {}
for word in list_b:
if( word in temp_dict ):
temp_dict[word]+=1
else:
temp_dict[word]=1
# frq is the number of appearances
for word, frq in temp_dict.iteritems():
if( frq > 1 ):
if( word in frq_dict )
frq_dict[word] += frq
else
frq_dict[word] = frq
else:
if( word in uqe_dict )
uqe_dict[word] += 1
else
uqe_dict[word] = 1https://stackoverflow.com/questions/41300583
复制相似问题