基于另一个列表计算嵌套列表中的元素
问题描述:
我试图根据不同的单词列表来计算嵌套列表中某个单词出现的次数。例如:基于另一个列表计算嵌套列表中的元素
one = [['apple','pear','bear'],['apple','drawers','bear','grapes']]
word = ['pear','oranges','pineapple','scones','drawers']
我要计算列表字每个字有多少次,在每种称为one
嵌套列表中出现。作为输出我想:
new_one = [[0,1,0],[0,1,0,0]]
我尝试使用.count
但.count
列表内不使用的元素,但单个字符串或整数。我无法使用for循环来使用.count()
来索引单词的元素。 Counter也是如此,它似乎不适用于嵌套列表或for循环。
我可以考虑使用字典,但最终我想new_one
是列表的列表,因为我想以后将new_one转换为矩阵,其中一行是矩阵的一行。
答
one = [['apple','pear','bear'],['apple','drawers','bear','grapes']]
word = ['pear','oranges','pineapple','scones','drawers']
output = []
# create a dict and populate with keys being unique words and values being its occurances
d = {}
for x in one:
for y in x:
d[y] = word.count(y)
# go through each word in sublist and find the count from the dict
for x in ne:
output.append([d[y] for y in x])
这应该给你:
output = [[[0, 1, 0], [0, 1, 0, 0]]]
答
这里是一个可能的方法:
[[[1 if z == x else 0 for z in y] for y in one] for x in word]
输出:
[[[0, 1, 0], [0, 0, 0, 0]],
[[0, 0, 0], [0, 0, 0, 0]],
[[0, 0, 0], [0, 0, 0, 0]],
[[0, 0, 0], [0, 0, 0, 0]],
[[0, 0, 0], [0, 1, 0, 0]]]
答
要做到这一点,最简单的方法是使用嵌套列表理解:
[[word.count(w) for w in l] for l in one]
这样做效率稍低,因为它每次都会计算每个词的出现次数(例如,它会执行两次word.count('apple')
),但是如果你的列表不是很长,那就不成问题了。
+0
这里是什么字?如果它涉及到嵌套列表,它就不起作用。 – song0089
答
首先我们重复列表,即一个。对于每个列表我们迭代的元素,即苹果梨熊等如果这匹配列表字,然后我们追加到临时列表new_one_temp。在每个外迭代中,我们追加到new_one列表。
one=[['apple','pear','bear'],['apple','drawers','bear','grapes']]
word=['pear','oranges','pineapple','scones','drawers']
new_one=[]
for list_elem in one:
new_one_temp=[]
for word_text in list_elem:
if word_text in word:
new_one_temp.extend([1])
else:
new_one_temp.extend([0])
new_one.append(new_one_temp)
print new_one
输出
new_one = [[0, 1, 0], [0, 1, 0, 0]]
这是伟大的,但可以这项工作时,苹果出现了两次? – song0089
当然!!如果“one”是苹果,苹果,梨,熊,梨,苹果,抽屉,熊,葡萄等],则输出在包含梨的新插槽中将包含1。尝试一下! :) –
哦,好吧,会有一种方法来计算他们虽然......?对于苹果,返回两个? – song0089