简体   繁体   中英

combine two lists in a dictionary - python

If I have two lists:

l_Y = [1, 2] 
l_Z = [3, 4]

what would be the easiest way to achieve this result?:

[{'a':1, 'b':1, 'c':'Y'}, {'a':2, 'b':2, 'c':'Y'}...
{'a':3, 'b':3, 'c':'Z'}, {'a':4, 'b':4, 'c':'Z'}]

Basically, if it's list l_Y then the value of c should be Y, if l_Z then the value of c should be Z.

I tried this:

[{'a':nb, 'b':nb, 'c':letter} for nb in [l_Y, l_Z] letter='Y' if nb is l_Y else 'Z']

but got a "SyntaxError"

nb returns the full list instead of an element anyway, so don't know how to do this...

Given this, I would do

[{'a':val,'b':val,'c':('Y' if lst==l_Y else 'Z')} for lst in (l_Y,l_Z) for val in lst]

In all honesty, though, as Blender mentions in his comment, you would probably be better off storing your lists in a dict, like this:

lists = {'Y':[1,2],'Z':[3,4]}

and do

[{'a':val,'b':val,'c':key} for key,item in lists.items() for val in item]

both result in

[{'a': 1, 'c': 'Y', 'b': 1}, {'a': 2, 'c': 'Y', 'b': 2}, {'a': 3, 'c': 'Z', 'b': 3}, {'a': 4, 'c': 'Z', 'b': 4}]

which I assume is what you were looking for.

The dict method has two benefits - it makes it cleaner to maintain (only one variable name floating in the namespace), and it makes the code much cleaner for the purposes of getting/retrieving the list.

The old method would require you to do this to get your list back from the results:

lst_that_was_passed_in = globals()['l_'+<Y or Z>]

while the newer method only requires lists[<Y or Z>] which makes it easier to maintain, cleaner on the namespace, and avoids crufts.

You could use the following (which doesn't require putting your lists into a dictionary or a conditional expression):

[{'a':v, 'b':v, 'c':c} 
    for (l, c) in zip((l_Y, l_Z), ('Y', 'Z')) 
        for v in l]

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