如何制作嵌套列表理解(Python)

时间:2017-07-22 02:35:04

标签: python list python-3.x dictionary list-comprehension

我有这本词典:

>>> times
{'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}

我想要输出,值的顺序很重要!

0 1 0 0 1 0 0 0 0
# 0 1 0 | 0 1 0 | 0 0 0     ===   time | time_d | time_up   items of the list

更确切地说,我想要一个这样的列表:

[0,1,0,0,1,0,0,0,0]

不使用print()

如果没有列表理解,我可以这样做:

tmp = []
for x in times.values():
    for y in x:
        tmp.append(y)

我尝试使用一些列表推导但是有人工作,就像这两个:

>>> [y for x in x for x in times.values()]
[0,0,0,0,0,0,0,0,0]

>>> [[y for x in x] for x in times.values()]
[[0,0,0],[0,0,0],[0,0,0]

如何在一行(列表理解)中解决这个问题?)

4 个答案:

答案 0 :(得分:3)

您已经根据字典了解了所需的值,因此在制作列表时,只需坚持显式关于字典的内容:

d = {'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}
v = [*d['time'], *d['time_d'], *d['time_up']]
print(v)

输出:

[0, 1, 0, 0, 1, 0, 0, 0, 0]

答案 1 :(得分:2)

如果我理解了这个问题,你必须取值,然后平坦:

  

编辑,用户@ juanpa.arrivillaga和@idjaw我认为我的问题更好,如果订单重要,那么你可以使用orderedDict:

import collections

times = collections.OrderedDict()

times['time'] = [0,1,0]
times['time_d'] = [0,1,0]
times['time_up'] = [0,0,0]

def get_values(dic):
  return [value for values in times.values() for value in values]


print(get_values(times))

现在,如果你更改了dict,结果按顺序排列:

times['time_up2'] = [0,0,1]

get_values(times)
它给了我:

  

[0,1,0,0,1,0,0,0,1]

如果订单无关紧要

times = {'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}

def get_values(dic):
  return [value for values in times.values() for value in values]


print(get_values(times))

答案 2 :(得分:0)

这也适用于Python 2:

[x for k in 'time time_d time_up'.split() for x in times[k]]

答案 3 :(得分:0)

从词典中取出keyvalue,然后将append放入列表中。

times={'time':[0,1,0], 'time_d':[0,1,0], 'time_up':[0,0,0]}
aa=[]
for key,value in times.iteritems():
    aa.append(value)
bb = [item for sublist in aa for item in sublist] #Making a flat list out of list of lists in Python
print bb

输出:

[0, 1, 0, 0, 0, 0, 0, 1, 0]