Wizard
Wizard

Reputation: 22063

Combine elements out of multiple lists?

Given multiple lists:

>>> foo = [hex, oct, abs, round, divmod, pow]
>>> bar = [format, ord, chr, ascii, bin]
and  others

I complete it with several nested condition

1.retrieve the variable from system

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'bar', 'foo']
>>> [e for e in dir() if '__' not in e]
['bar', 'foo']
>>> mul_list =  [e for e in dir() if '__' not in e]
>>> mul_list
['bar', 'foo']

2.obtain each element with nested condition

>>> [ e.__name__ for single_list in mul_list for e in eval(single_list)]
['format', 'ord', 'chr', 'ascii', 'bin', 'hex', 'oct', 'abs', 'round', 'divmod', 'pow']

How to extract with simple code elegantly?

Upvotes: 0

Views: 85

Answers (3)

Kallz
Kallz

Reputation: 3523

frist change

mul_list =  [e for e in dir() if '__' not in e]

To

mul_list =  [e for e in dir() if '__' not in e and isinstance(eval(e),list)]

so always get the only list in mul_list

@coldspeed check it

>>> foo = [hex, oct, abs, round, divmod, pow]
>>> fred = ['one', 'two', 'three']
>>> jim = [1, 2, 3]
>>> mul_list =  [e for e in dir() if '__' not in e]
>>> [ e.__name__ for list_name in mul_list for e in globals()[list_name]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute '__name__'
>>> mul_list
['foo', 'fred', 'jim']

Upvotes: 1

N M
N M

Reputation: 616

You can just concatenate lists using the + operator. So,

multlist = []
for e in dir():
    if "__" not in e:
        if type(eval(e)) == type(multlist)
            multlist += eval(e)

Upvotes: 0

cs95
cs95

Reputation: 402333

I'm not sure about a simpler way, but you should consider accessing globals as an alternative to using eval:

[ e.__name__ for list_name in mul_list for e in globals()[list_name]]

Upvotes: 1

Related Questions