如何在python中返回元组中的对象列表?

2024-04-18 15:58:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点被python问题难住了。我想编写一个函数,返回嵌套在元组中的所有对象的列表。你知道吗

例如,我希望能够将元组(((2,4),6,(9,(3,7)))转换为[2,4,6,9,3,7]。然而,我真的不确定如何开始,因为元组是不可变的。谢谢!你知道吗


Tags: 对象函数列表元组
3条回答

您需要展平元组中的元组,请参见Flattening a shallow list in Python和James Brady提供的解决方案:

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

一个非常基本的答案,但是应该按照你的要求去做。使用tryexcept查看项是否可iterable。如果为True,则递归函数;如果为False,则将项添加到列表中。你知道吗

iterable = (((2,4),6,(9,(3,7))))
_list = []


def addToList(elem, listRef):
    """
    elem: item you want to insert into the list
    listRef: list you want to append stuff to
    """
    try:
        for x in elem:
            addToList(x, listRef)    # recursive call
    except:
        listRef.append(elem)    # add the item if it's not iterable


# Main
for item in iterable:
    addToList(item, _list)    # iterate tuple, pass ea. element into addToList, pass the list you want to append to
print _list

Python的经验法则,快速失败和廉价失败:)

警告:如果元组中有字符串,则每个字符都将附加到_list(因为字符串是iterable)。我没有围绕字符串进行设计,因为您没有指定是否使用它们。你知道吗

这是一个递归的好例子——尽管尼古拉斯已经有了类似的答案。你知道吗

在这里,我们为您提供的元组设置了一个。我们还设置了一个空列表,您需要在其中输入元组。你知道吗

函数从元组开始,循环遍历每个元素。如果元素是一个元组,它会再次递归调用函数,直到找到一个非元组。然后将其插入列表中。你知道吗

tup = (((2,4),6,(9,(3,7))))
listversion = []
def loopthroughtup(tup):
    for i in tup:
        if type(i) == tuple:
            print str(i) + " is a tuple"
            loopthroughtup(i)
        else:
            print str(i) + " is not a tuple"
            listversion.append(i)

loopthroughtup(tup)
print listversion

相关问题 更多 >