简体   繁体   中英

Python: creating empty lists within empty lists?

EDIT: so I figured out that if I declare this at the beginning it works fine:

RelayPlaceHolder = [[],[],[],[],[],[],[],[],[]]

Why can't something like this create the same sort of empty containers? the number of empty lists might change:

for SwimTeams in SwimTeamList:
                empty = []
                RelayPlaceHolder.append(empty)

this was my old question...


I have a list of lists of further lists of single dictionaries:

TeamAgeGroupGender[team#][swimmer#][their dictionary with a key such as {"free":19.05}]

I have a loop that for every team in the first level of my lists, it then loops through every swimmer within that team's list, and add's their swim that corresponds to the key value "free" to a new list called RelayPlaceHolder[teamid][***the thing I just added***]

    for SwimTeams in SwimTeamList:
            empty = []
            RelayPlaceHolder.append(empty)
            teamid = SwimTeamList.index(SwimTeams)
            print SwimTeams
            print teamid

            for swimmers in TeamAgeGroupGender[teamid]:
                swimmerID = TeamAgeGroupGender[teamid].index(swimmers)
                RelayPlaceHolder[teamid].append({SwimTeams:TeamAgeGroupGender[teamid][swimmerID]["Free"]})
            print RelayPlaceHolder[teamid][0]

Desired:

RelayPlaceHolder[0][*** list of swims that go with this team#0 ***] 
RelayPlaceHolder[1][*** list of swims that go with team#1, ie the next teamid in the loop***]

for some reason, my loop is only adding swims to RelayPlaceHolder[0] , even the swims from team#1. I tried using the print to troubleshoot, however, the teamid index and swimteam names are changing just fine from #0 to #1, however, my RelayPlaceHolder[teamid].append is still adding to the #0 list and not the #1. I also know this because a key value from later code is failing to find the correct key in RelayPlaceHolder[1] (because its turning up empty). I'm not sure why my loop is failing. I've used similar structure in other loops...

Thank you.

As commented by @doukremt: A concise syntax if you need to define an arbitrary number of lists is:

[[] for i in range(some_number)]

If you need to do it more often, you can implement it in a function:

>>> lists = lambda x: [[] for i in range(x)]
>>> lists(3)
[[], [], []]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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