Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:获取字符串列表的列表索引计数_Python - Fatal编程技术网

Python:获取字符串列表的列表索引计数

Python:获取字符串列表的列表索引计数,python,Python,我有以下几点 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" ] 作为一个例子,我想做的是把这些单词放到另一个dic

我有以下几点

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"
]
作为一个例子,我想做的是把这些单词放到另一个dict或复杂dict中,每次找到一个单词,但它所在句子的索引计数

{
  a: [0,1,2],
  see: [1,2,2],
  me: [2]
}
单词=[a,看,我] 句子=[ 一条狗进了家。, 我看到一条狗在我周围,我也能看到那条狗, 这条狗能用骨头看见我 ]


这管用

您可以为每个句子创建计数器,迭代这些计数器并检查它是否存在,这样您就可以通过嵌套理解来完成:

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]}

你的代码在哪里?这背后的逻辑是什么:a:[0,1,2]?我认为see应该是[1,1,2],对吗?请看一个问题并表示欢迎!对不起,你问的不是我们的事。请查看并从中删除。演示如何解决这个编码问题?堆栈溢出的主题已关闭。您必须诚实地尝试解决方案,然后询问有关实现的具体问题。堆栈溢出不是为了取代现有的教程或文档,也不是为您完成研究、设计或编码工作的一种方式。那么,有什么不对呢。
{'a': [0, 1, 2], 'see': [1, 1, 2], 'me': [2]}