如何在Python中将一个嵌套的元组和列表转换为列表的列表?

4
我有一个包含列表和元组的元组。我需要将它转换为具有相同结构的嵌套列表。例如,我想将 (1,2,[3,(4,5)]) 转换为 [1,2,[3,[4,5]]]
在Python中,我该如何做到这一点?

8
我知道答案,但我会先给你一个机会发布你的解决方案。 - SilentGhost
1
亲爱的吉米尔,这将是)(tsil。 - SilentGhost
S.Lott - 你需要比我给出的例子更多吗?基本上,我想将一个包含列表和元组的数据结构转换为只有列表(所以表示形式中的'('和')'会被转换为'['和']')。 - Daryl Spitzer
以前我发过一个问题,然后立刻回答了它,结果引起了一些抱怨。所以这次我想先留出时间给其他人回答。至少这次评论者有点幽默感。 - Daryl Spitzer
这个问题有什么问题导致它应该得到-4票? - Daryl Spitzer
显示剩余4条评论
4个回答

22
def listit(t):
    return list(map(listit, t)) if isinstance(t, (list, tuple)) else t

我能想象到的最简短的解决方案。

map()函数总是返回一个列表。应该使用map( ...)而不是list(map( ... ))。 - Nicolas Dumazet
2
如果你使用的是 Python 2.x,那么 NicDumZ 是正确的。但在 Python 3.x 中,map() 返回一个生成器。 - DasIch
和克里斯蒂安的答案有什么不同? - SilentGhost
listit(('AB'))返回的是'AB',而不是应该返回['AB']。 - CPBL
1
@CPBL 请尝试使用listit(('AB',))。你的写法中,你将'AB'放在括号中传递,而不是单元素元组('AB',)。 - Aaron

8
作为一个 Python 新手,我会尝试这个。
def f(t):
    if type(t) == list or type(t) == tuple:
        return [f(i) for i in t]
    return t

t = (1,2,[3,(4,5)]) 
f(t)
>>> [1, 2, [3, [4, 5]]]

或者,如果你喜欢一行代码:

def f(t):
    return [f(i) for i in t] if isinstance(t, (list, tuple)) else t

5
为了检查一个对象的类型,最好使用isinstance()函数。作为一个额外的功能,你甚至可以一次检查多个类型,就像这样:isinstance(t, (list, tuple))。 - efotinis
hasattr(t,'iter') perhaps - Jimmy
1
@Jimmy hasattr(t,'iter') 太多余了,因为字符串也是可迭代的(通常情况下你不想将它们转换为字符列表)。 - bernard paulus

2
我们可以(滥用)利用这样一个事实,即json.loads总是将JSON列表转换为Python列表,而json.dumps将任何Python集合转换为JSON列表:
import json

def nested_list(nested_collection):
    return json.loads(json.dumps(nested_collection))

0

这是我想到的,但我喜欢其他的更好。

def deep_list(x):
      """fully copies trees of tuples or lists to a tree of lists.
         deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]
         deep_list( (1,2,[3,(4,5)]) ) returns [1,2,[3,[4,5]]]"""
      if not ( type(x) == type( () ) or type(x) == type( [] ) ):
          return x
      return map(deep_list,x)

我看到aztek的答案可以缩短为:

def deep_list(x):
     return map(deep_list, x) if isinstance(x, (list, tuple)) else x

更新:但是现在我从DasIch的评论中看到,在Python 3.x中这不起作用,因为map()返回一个生成器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接