2017-08-14 81 views
0

鉴于多个列表:组合多个列表中的元素?

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

我与几个嵌套的条件

每个元素具有嵌套条件完成它1.retrieve可变从系统

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

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

如何用简单的代码提取e legantly?

回答

1

我不知道一个简单的方法,但你应该考虑访问globals作为替代使用eval

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

您是否尝试运行此代码,因为我在运行时遇到了错误 – Kallz

+0

@Kallz如果'__'不在e]中,您需要在dir()中执行mul_list = [e for e]。 –

+0

检查我的答案,给我错误 – Kallz

0

你可以只使用串联+运算符列表。 所以,

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

弗里斯特变化

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

' [hex,oct,abs,round,divmod,pow]'是一个模块列表。所以'e .__ name__'的作品。 –

+0

@cᴏʟᴅsᴘᴇᴇᴅ然后我怎么能解决这个问题 – Kallz

+0

如果你想解决这个问题,那么它就可以解决这个问题,那么很明显'['one','two','three']'和'[1,2,3]'不应该使用,因为它们不是模块列表。 –

相关问题