2014-11-20 129 views
0

如果我有轉換的混合嵌套列表嵌套元組

​​3210

,並希望有

(('foo', 'bar'), ('foofoo', 'barbar')) 

我可以做

tuple(tuple(i) for i in easy_nested_list) 

但如果我有

mixed_nested_list = [['foo', 'bar'], ['foofoo', ['foo', 'bar']],'some', 2, 3] 

並且想用這個構建一個元組,我不知道該如何開始。

這將是很好得到:

(('foo', 'bar'), ('foofoo', ('foo', 'bar')), 'some', 2, 3) 

的第一個問題就是,Python變成我的字符串到每個字符的元組。第二件事是我得到

TypeError: 'int' object is not iterable 

回答

8

轉換遞歸,並測試列表:

def to_tuple(lst): 
    return tuple(to_tuple(i) if isinstance(i, list) else i for i in lst) 

這將產生一個給定列表中的元組,而是使用遞歸調用轉換任何嵌套list對象。

演示:

>>> def to_tuple(lst): 
...  return tuple(to_tuple(i) if isinstance(i, list) else i for i in lst) 
... 
>>> mixed_nested_list = [['foo', 'bar'], ['foofoo', ['foo', 'bar']],'some', 2, 3] 
>>> to_tuple(mixed_nested_list) 
(('foo', 'bar'), ('foofoo', ('foo', 'bar')), 'some', 2, 3) 
+0

酷,這是非常好的!謝謝! – Finn 2014-11-20 21:55:07