2017-08-14 117 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]'不應該使用,因爲它們不是模塊列表。 –