[英]Python: Get list index count for a list of strings
我有以下..
words = ["a", "see", "me"]
sentances = [
"a dog goes into the home.",
"I see a dog around me, I can also see the dog",
"The dog can see me with a bone"
]
作為一個例子,我想要做的是將這些單詞放入另一個字典或復雜的字典中,每次找到一個單詞但它所在的句子的索引計數
{
a: [0,1,2],
see: [1,2,2],
me: [2]
}
words = ["a", "see", "me"] sentances = ["一只狗進了家。","我看到一只狗在我身邊,我也可以看到狗","狗可以看到我有骨頭”]
res = {}
for i in range(len(sentances)):
sentance = sentances[i]
sentance = sentance.split()
for word in sentance:
if word in words:
try:
res[word].append(i)
except:
res[word] = [i]
print(res)
# {'a': [0, 1, 2], 'see': [1, 1, 2], 'me': [2]}
這行得通!
您可以為每個句子制作計數器,迭代這些Counters
並檢查它是否存在,因此您可以使用嵌套理解來完成:
from collections import Counter
words = ["a", "see", "me"]
sentances = [
"a dog goes into the home.",
"I see a dog around me, I can also see the dog",
"The dog can see me with a bone"
]
sentances_counter = list(map(lambda s: Counter(s.split()), sentances))
result = {
word: [index for index, sentence in enumerate(sentances_counter) if word in sentence for _ in range(sentence[word])]
for word in words
}
print(result)
這給了我:
{'a': [0, 1, 2], 'see': [1, 1, 2], 'me': [2]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.