Frank,

Given this kind of data: d = {1: ['aaa', 'bbb', 'ccc'], 2: ['fff', 'ggg']}

You seem focused on a one-liner, however ridiculous or inefficient. Does this 
count as a somewhat weird one liner?

comb = [];   _ = [comb.append(v) for v in d.values()]

If you run the code and ignore the returned result, the value in comb is:

print(comb)

[['aaa', 'bbb', 'ccc'], ['fff', 'ggg']]

As discussed the other day here, this is an example of a variant on the 
anonymous function discussion as what is wanted is a side effect. I could omit 
assigning the result to anything and run this code after the previous like this:

[comb.append(v) for v in d.values()]
[None, None]
comb
[['aaa', 'bbb', 'ccc'], ['fff', 'ggg'], ['aaa', 'bbb', 'ccc'], ['fff', 'ggg']]

As shown the list comprehension itself is not returning anything of value and 
need not be assigned to anything. But it then generally is set to autoprint and 
that can be supressed by assigning the value to _ or anything you can ignore.

I am NOT saying this is a good way but that it is sort of a one-liner. There 
are good reasons I do not see people doing things this way!

-----Original Message-----
From: Frank Millman <fr...@chagford.com>
To: python-list@python.org
Sent: Tue, Feb 22, 2022 4:19 am
Subject: One-liner to merge lists?


Hi all



I think this should be a simple one-liner, but I cannot figure it out.



I have a dictionary with a number of keys, where each value is a single 

list -



 >>> d = {1: ['aaa', 'bbb', 'ccc'], 2: ['fff', 'ggg']}



I want to combine all values into a single list -



 >>> ans = ['aaa', 'bbb', 'ccc', 'fff', 'ggg']



I can do this -



 >>> a = []

 >>> for v in d.values():

...   a.extend(v)

...

 >>> a

['aaa', 'bbb', 'ccc', 'fff', 'ggg']



I can also do this -



 >>> from itertools import chain

 >>> a = list(chain(*d.values()))

 >>> a

['aaa', 'bbb', 'ccc', 'fff', 'ggg']

 >>>



Is there a simpler way?



Thanks



Frank Millman





-- 

https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to