Python:在空列表中创建空列表?

时间:2014-01-30 01:43:21

标签: python list loops

编辑:所以我发现如果我在开始时声明它,它可以正常工作:

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

为什么这样的东西不能创建相同类型的空容器?空列表的数量可能会改变:

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

这是我的老问题......


我列出了单个词典的更多列表:

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

我有一个循环,对于我的列表的第一级中的每个团队,然后循环遍历该团队列表中的每个游泳者,并将他们的游泳对应于关键值“free”添加到名为{{的新列表中1}}

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]

由于某种原因,我的循环只是将游泳添加到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***] ,甚至是来自团队#1的游泳。我尝试使用打印进行故障排除,但RelayPlaceHolder[0]索引和teamid名称从#0改为#1正常,但是,我的swimteam仍在添加到#0列表而不是#1。我也知道这一点,因为后来的代码中的键值无法在RelayPlaceHolder[teamid].append中找到正确的键(因为它变为空)。我不知道为什么我的循环失败了。我在其他循环中使用了类似的结构......

谢谢。

1 个答案:

答案 0 :(得分:0)

由@doukremt评论:如果需要定义任意数量的列表,则使用简洁的语法:

[[] for i in range(some_number)]

如果您需要更频繁地执行此操作,可以在函数中实现它:

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