简体   繁体   中英

How to make a nested list comprehension (Python)

I have this dictionary:

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

I want to make this output, the order of the values matters! :

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

For been more exactly I want a list like this:

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

Not use print() .

Without a list comprehension I can do:

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

I tryied using some list comprehensions but anyone works, like this two:

>>> [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]

How can I solve this with in one line (list comprehension))?

You already know what values you want based on your dictionary, so just stick to being explicit about what you want from your dictionary when crafting your list:

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)

Output:

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

If I understood the question, you have to take the values, and then flat:

Edit, with users @juanpa.arrivillaga and @idjaw I think I undertand better the question, if the order matters , so you can use 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))

Now, if you change the dict, the result came in order:

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

get_values(times)

it gives me:

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

If the order doesn't matter :

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))

在Python 2中也可以使用:

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

Take key and value from dictionary and append it into a list.

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

Output:

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

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