为元素列表中的每个单词返回(单词)所在的“列表元素”的索引

2024-04-19 21:09:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的列表,其中每个元素字符串中的第一个数字正好是每个元素的索引:

list = [" ","1- make your choice", "2- put something and make", "3- make something happens", "4- giulio took his choice so make","5- make your choice", "6- put something and make", "7- make something happens", "8- giulio took his choice so make","9- make your choice", "10- put something and make", "11- make something happens", "12- giulio took his choice so make"]

我想为element list中的每个单词返回(单词)所在的“element of list”索引:

for x in list:
    ....

我的意思是这样的:

position_of_word_in_all_elements_list = set("make": 1,2,3,4,5,6,7,8,9,10,11,12)    

position_of_word_in_all_elements_list = set("your": 1,5,9)

position_of_word_in_all_elements_list = set("giulio":4,8,12)

有什么建议吗?你知道吗


Tags: andofinyourmakesoputposition
3条回答

这将为输入中的所有字符串查找匹配项,即使是“1-”等。但是从结果中筛选您不喜欢的记录应该不是什么大问题:

# find the set of all words (sequences separated by a space) in input
s = set(" ".join(list).split(" "))

# for each word go through input and add index to the 
# list if word is in the element. output list into a dict with
# the word as a key
res = dict((key, [ i for i, value in enumerate(list) if key in value.split(" ")]) for key in s)

{'': [0], 'and': [2, 6, 10], '8-': [8], '11-': [11], '6-': [6], 'something': [2, 3, 6, 7, 10, 11], 'your': [1, 5, 9], 'happens': [3, 7, 11], 'giulio': [4, 8, 12], 'make': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], '4-': [4], '2-': [2], 'his': [4, 8, 12], '9-': [9], '10-': [10], '7-': [7], '12-': [12], 'took': [4, 8, 12], 'put': [2, 6, 10], 'choice': [1, 4, 5, 8, 9, 12], '5-': [5], 'so': [4, 8, 12], '3-': [3], '1-': [1]}

首先,将列表重命名为不干扰Python内置内容 所以呢

>>> from collections import defaultdict
>>> li = [" ","1- make your choice", "2- put something and make", "3- make something happens", "4- giulio took his choice so make","5- make your choice", "6- put something and make", "7- make something happens", "8- giulio took his choice so make","9- make your choice", "10- put something and make", "11- make something happens", "12- giulio took his choice so make"]`
>>> dd = defaultdict(list)
>>> for l in li:
        try: # this is ugly hack to skip the " " value
            index,words = l.split('-')
        except ValueError:
            continue
        word_list = words.strip().split()
        for word in word_list:
            dd[word].append(index)
>>> dd['make']
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']

defaultdict的作用: 只要字典中有关键字(在本例中是单词),它就可以像普通字典一样工作。如果键不存在,它将创建它,其值对应于在声明它时指定的空列表dd = defaultdict(list)。我不是最好的解释者,所以如果不清楚的话,我建议在其他地方读一下defauldict:)

@奥列格写了一个很棒的书呆子解决方案。我想出了以下解决这个问题的简单方法。你知道吗

def findIndex(st, lis):
    positions = []
    j = 0
    for x in lis:
        if st in x: 
            positions.append(j)
            j += 1
    return positions

$>>> findIndex('your', list)

[1, 5, 9]

相关问题 更多 >