将混合的嵌套列表转换为嵌套元组 [英] Convert a mixed nested list to a nested tuple
本文介绍了将混合的嵌套列表转换为嵌套元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有
easy_nested_list = [['foo', 'bar'], ['foofoo', 'barbar']]
并希望拥有
(('foo', 'bar'), ('foofoo', 'barbar'))
我能做
tuple(tuple(i) for i in easy_nested_list)
但是如果我有
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.
很高兴得到:
(('foo', 'bar'), ('foofoo', ('foo', 'bar')), 'some', 2, 3)
第一个问题是Python将我的字符串转换为每个字符的元组.第二件事是我得到
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
推荐答案
递归转换并测试列表:
def to_tuple(lst):
return tuple(to_tuple(i) if isinstance(i, list) else i for i in lst)
这会为给定列表生成一个元组,但是会使用递归调用转换任何嵌套的list
对象.
This produces a tuple for a given list, but converts any nested list
objects using a recursive call.
演示:
>>> 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)
这篇关于将混合的嵌套列表转换为嵌套元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文