[英]creating empty lists of lists in python
I have a dictionary like this:我有一本这样的字典:
data = {
'Sim_1':{
'sig1':[
1,
2,
3
],
'sig2':[
4,
5,
6
]
},
'Sim_2':{
'sig3':[
7,
8,
9
],
'sig4':[
10,
11,
12
]
},
'Com_1':{
'sig5':[
13,
14,
15
],
'sig6':[
16,
17,
18
]
},
'Com_2':{
'sig7':[
19,
20,
21
],
'sig8':[
128,
23,
24
]
}
}
I want to create a list variable like this:我想创建一个这样的列表变量:
x=[[],[],[],[],[],[],[],[]]
Basically I want to create a list of empty lists whose length is equal to the number of keys in the dictionary which I have mentioned above.基本上我想创建一个空列表的列表,其长度等于我上面提到的字典中的键数。 Here the thing is the dictionary may vary.
这里的事情是字典可能会有所不同。 That is the number of signals in each dictionary inside the dictionary 'data' can vary.
也就是说,字典“数据”中每个字典中的信号数量可能会有所不同。
x = []
for _ in range(len(data)):
x.append([])
List comprehensions are great for moving through multidimensional data structures like this.列表推导式非常适合在这样的多维数据结构中移动。
In this case it's a two-tiered data structure so you need two inner for
loops.在这种情况下,它是一个两层数据结构,因此您需要两个内部
for
循环。
>>> [[] for simcom in data.values() for sig in simcom ]
[[], [], [], [], [], [], [], []]
It's really nice because if you keep them simple you can read them off like an English phrase.这真的很好,因为如果你让它们保持简单,你可以像读英语短语一样阅读它们。 The above says
上面说
An empty list for each sim/com which is a value in my data dict, for each signal within this sim/com.
每个 sim/com 的空列表,这是我的数据字典中的一个值,对于这个 sim/com 中的每个信号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.