简体   繁体   English

Python:如何在重复的列表中始终找到下一个索引?

[英]Python: How do I consistently find the next index after another index in a list with duplicates?

Sorry if the question wasn't clear enough, I am very new to python. 抱歉,如果这个问题不够清楚,我对python还是很陌生。 I also apologize in advance if there are any typos in my code. 如果我的代码中有错字,我也提前致歉。

Say I have a list 说我有一个清单

list = [a,b,c,a,x,y,b,m,a,z]

And I want to get the index value of the element after each 'a' using a for loop and store it in a dict. 我想使用for循环获取每个“ a”之后的元素的索引值,并将其存储在dict中。 (This assumes dict = {} already exists) (假设dict = {}已经存在)

for store in list:
    if dict.has_key(store) == False:
        if list.index(store) != len(list)-1:
            dict[store] = []
            dict[store].append(list[list.index(store)+1])
    else:
        if list.index(store) != len(list)-1:
            dict[store].append(list[list.index(store)+1])

Now ideally, I would want my dict to be 现在理想情况下,我希望我的字典是

dict = {'a':['b','x','z'], 'b':['c','m'], 'c':['a']....etc.}

Instead, I get 相反,我得到

dict = {'a':['b','b','b'], 'b':['c','c'], 'c':['a']...etc.}

I realized this is because index only finds the first occurrence of variable store. 我意识到这是因为索引仅找到变量存储的首次出现。 How would I structure my code so that for every value of store I can find the next index of that specific value instead of only the first one? 我将如何构造我的代码,以便对于存储的每个值,我都能找到该特定值的下一个索引,而不仅仅是第一个索引?

Also, I want to know how to do this only using a for loop; 另外,我想知道如何仅使用for循环来执行此操作; no recursions or while, etc (if statements are fine obviously). 没有递归或时间,等等(如果语句显然可以)。

I apologize again if my question isn't clear or if my code is messy. 如果我的问题不清楚或代码混乱,我再次道歉。

You can do it like that: 您可以这样做:

l = ['a','b','c','a','x','y','b','m','a','z']
d={}
for i in range(len(l)-1):
    if not l[i] in d:
        d[l[i]] = []
    d[l[i]].append(l[i+1])

Then d is 那么d

{'a': ['b', 'x', 'z'],
 'b': ['c', 'm'],
 'c': ['a'],
 'm': ['a'],
 'x': ['y'],
 'y': ['b']}

Regarding your code, there is no need to use index , as you already enumerating over the list, so you do not need to search for the place of the current element. 关于您的代码,由于已经在列表中进行了枚举,因此无需使用index ,因此无需搜索当前元素的位置。 Also, you can just enumerate until len(l)-1 , which simplifies the code. 同样,您可以枚举直到len(l)-1 ,从而简化了代码。 The problem in your code was that list.index(store) always finds the first appearance of store in list . 在你的代码的问题是, list.index(store)总能找到第一个出场storelist

This looks like a job for defaultdict . 这看起来像是defaultdict的工作。 Also, you should avoid using list and dict as variables since they are reserved words. 另外,您应该避免将listdict用作变量,因为它们是保留字。

from collections import defaultdict

# create a dictionary that has default value of an empty list
# for any new key
d = defaultdict(list)

# create the list
my_list = 'a,b,c,a,x,y,b,m,a,z'.split(',')

# create tuples of each item with its following item
for k,v in zip(my_list, my_list[1:]):
    d[k].append(v)

d 
# returns:
defaultdict(list,
            {'a': ['b', 'x', 'z'],
             'b': ['c', 'm'],
             'c': ['a'],
             'm': ['a'],
             'x': ['y'],
             'y': ['b']})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM