d = {'a':[1,2,3], 'b':[4,5]}
and I need
[1,2,3,4,5]
using list comprehension. How do I do it?
Use a nested list comprehension:
>>> [val for lst in d.values() for val in lst]
[1, 2, 3, 4, 5]
But you may need to sort the dictionary first (because dicts are unordered) to guarantee the order:
>>> [val for key in sorted(d) for val in d[key]]
[1, 2, 3, 4, 5]
Easy and one liner solution using list comprehension :
>>> sorted([num for val in d.values() for num in val])
[1, 2, 3, 4, 5]
sum(d.values(),[])
works but not performant because it applies a = a + b
for each temp list.
Use itertools.chain.from_iterable
instead:
import itertools
print(list(itertools.chain.from_iterable(d.values())))
or sorted version:
print(sorted(itertools.chain.from_iterable(d.values())))
If the order of elements is not important, then you cannot beat this:
sum(d.values(), [])
(Add sorted()
if necessary.)
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.