【问题标题】:Python: converting list of lists to tuples of tuplesPython:将列表列表转换为元组的元组
【发布时间】:2011-07-27 06:20:14
【问题描述】:

Python 新手!我需要帮助转换列表元组的列表。

我想调用 append_as_tuples 函数,但每次我返回它时,它都会说
它只能将列表(不是元组)连接到列表

这是我目前所拥有的:

def append_as_tuple(t, l):
    ''' Convert list l to a tuple and append it to tuple t as a single value '''
    return t[:] + (tuple(l),)  

def convert_lists(lol):
    t = []
    if type(lol) == a or type(lol) == tuple:
        return [convert_lists(lol) for i in t]
    return append_as_tuples(lol,a)

#- test harness#

a=[range(5), range(10,20), ['hello', 'goodbye']]  
print a  
print convert_lists(a)  
print convert_lists([])  

【问题讨论】:

  • 您的if type(lol) == a 完全错误;它似乎起作用只是因为您的“测试工具”中有一个名为a的全局变量,而a不是type实例......所以测试将是False .如果没有全局 a,它会引发异常。

标签: python list function tuples


【解决方案1】:

有一个python内置函数: 列表和元组

list( 元组)...将元组转换为列表 tuple( the list )....将列表转换为元组

【讨论】:

  • 这会将最外面的列表转换为元组(反之亦然)。但是,内部列表/元组将保持其原始类型。
【解决方案2】:

要将list_of_lists 转换为元组的元组,请使用

tuple_of_tuples = tuple(tuple(x) for x in list_of_lists)

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多