Convert a mixed nested list to a nested tuple

烂漫一生 提交于 2019-12-08 11:40:36

问题


If I have

easy_nested_list = [['foo', 'bar'], ['foofoo', 'barbar']]

and would like to have

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

I can do

tuple(tuple(i) for i in easy_nested_list)

but if I have

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

and would like to build a tuple out of this, I don't know how to start.

It would be nice to get:

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

The first problem is that Python turns my string into a tuple for each character. The second thing is I get

TypeError: 'int' object is not iterable

回答1:


Convert recursively, and test for lists:

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

This produces a tuple for a given list, but converts any nested list objects using a recursive call.

Demo:

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


来源:https://stackoverflow.com/questions/27049998/convert-a-mixed-nested-list-to-a-nested-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!