繁体   English   中英

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

[英]Python: creating empty lists within empty lists?

编辑:所以我发现,如果我在一开始就声明了它,效果很好:

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

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

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

这是我的老问题...


我有一个列表,进一步列出了单个词典:

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

我有一个循环,对于列表中第一级的每个团队,然后循环浏览该团队列表中的每个游泳者,并将与键值“ free”相对应的他们的游泳添加到名为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***]

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

谢谢。

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

[[] for i in range(some_number)]

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

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

暂无
暂无

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

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