从多个列表中组合元素?

时间:2017-08-14 03:14:46

标签: python

给出多个列表:

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

我用几个嵌套条件

完成它

1.从系统中检索变量

>>> 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.使用嵌套条件获得每个元素

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

如何优雅地提取简单的代码?

3 个答案:

答案 0 :(得分:1)

我不确定更简单的方法,但您应该考虑使用globals作为使用eval的替代方法:

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

答案 1 :(得分:1)

frist change

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

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

所以总是得到mul_list中唯一的列表

@coldspeed检查

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

答案 2 :(得分:0)

您可以使用+运算符连接列表。 所以,

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