简体   繁体   English

多个 python 嵌套 for 循环,可能递归遍历列表。 蟒蛇 3

[英]Multiple python nested for loops, possibly recursively traverse lists. python 3

I am trying to match the first item in participantId to the first list in str(each['participantId']).我试图将participantId 中的第一个项目与str(each['participantId']) 中的第一个列表相匹配。 And then the second item in participantId to second list, and so on.然后将participantId 中的第二项添加到第二个列表中,依此类推。

participantId = ['2','5','7','4','10','9','2']

each['participantId'] = [[1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10],
                         [1,2,3,4,5,6,7,8,9,10]]

So I want to use a for loop on participantId but have just the first item in the list do an if statement with the first list, then the second item in participantId do an if statement with the second list.所以我想在participantId 上使用for 循环,但只有列表中的第一项对第一个列表执行if 语句,然后participantId 中的第二项对第二个列表执行if 语句。 As of Now my code just matches all participantId's with each list.截至目前,我的代码仅将所有参与者 ID 与每个列表相匹配。 here is a snippet of my code:这是我的代码片段:

for each in json['participants']:
                for x in str(each['participantId']):
                    print(x)
                    for i in participantId:
                       if x == i:
                            kills = each['stats']['deaths']
                            print('kills')
                            print(kills)

I have looked at recursively traverse lists as a solution but I cant seem to make that work.我已经将递归遍历列表视为一种解决方案,但我似乎无法做到这一点。 I'm very new to python and coding so maybe there is some function im missing.我对python和编码很陌生,所以也许我缺少一些功能。

I would recommend using dictionary comprehension for something like this.我建议使用字典理解来处理这样的事情。
For example:例如:

participant_data = {
        _id: data for _id, data in \
        zip(participantId, each['participantId'])
        }

will make participant_data a dictionary where the keys are the items in participantId , and the values are the items in each['participantId'] .将使participant_data成为一个字典,其中键是participantId中的项,值是each['participantId'] To get the data for a specific id, you just need to use participant_data[id_of_participant] .要获取特定 id 的数据,您只需要使用participant_data[id_of_participant]

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

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