我有这样一个列表,其中每个元素的字符串中的第一个数字正好是每个元素的索引:
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"]我希望为元素列表中的每个单词返回“元素列表”的索引,其中(单词)位于:
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)有什么建议吗?
发布于 2015-10-25 17:36:24
这将发现输入中的所有字符串都会出现,甚至是"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){“:”、“和”:2、6、10、‘8 -’、' 11 -':11、‘6 -’、‘6 -’、‘某事’:2、3、6、7、10、11、‘你’:1、5、9、‘发生’:3、7、11、'giulio':4、8、12、'make':1、2、3、4、5、6、7、8、9、10、11、12、‘4 -’“2-”:2,“他的”:4,8,12,“9-”:9,'10-':10,'7-':7,‘12-’12,‘拿走’:4,8,12,'put':2,6,10,‘选择’:1,4,5,8,9,12,‘5-’‘5,’5‘,'so':4,8,12,'3-':3,'1-':1}
发布于 2015-10-25 17:44:10
首先,将列表重命名为不干扰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)时所指定的那样。我不是最好的解释者,所以如果不清楚的话,我建议在其他地方阅读默认的内容:)
发布于 2015-10-25 17:45:41
@Oleg写了一个很棒的书呆子解决方案。我想出了以下解决这个问题的简单方法。
def findIndex(st, lis):
positions = []
j = 0
for x in lis:
if st in x:
positions.append(j)
j += 1
return positions$>>> findIndex(“您”,列表) 1、5、9
https://stackoverflow.com/questions/33332647
复制相似问题