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