【问题标题】:Swap positons on two lists stored in tuple交换存储在元组中的两个列表的位置
【发布时间】:2020-02-02 05:58:02
【问题描述】:

我有一个包含多个列表的元组,我需要动态交换两个列表中项目的值。例如,tuple_of_lists = (**list1**:[1,1,1],list2:[2,2,2],**list3**:[3,3,3]) 我需要能够输入 --swap x & y (1,3)-- 并且在不更改列表名称的情况下,输出 (**list1**:[3,3,3],list2:[2,2,2],**list3**:[1,1,1])

对 python 还是很陌生(和一般的编码),我认为我缺少一些关于数据结构的东西。

我正在尝试使用类似的东西:

intermediary = tuple_of_lists[1] 
tuple_of_lists[1] = list(tuple_of_lists[3]) 
tuple_of_lists[3] = list(intermediary)

但我收到元组不接受赋值的错误 - 即使它只是实际被更改的列表?有没有简单的解决方法?

【问题讨论】:

  • list_of_lists = list(tuple_of_lists)

标签: python data-structures tuples assign


【解决方案1】:

元组是不可变的,所以你不能改变它们的元素。然而,列表是可变的。

你可以做的是从你的元组创建一个列表,交换元素并将列表转换回一个元组:

tuple_of_lists = ([1,1,1], [2,2,2], [3,3,3])
lt =  list(tuple_of_lists)                    #create list from tuple
lt[2],lt[0] = lt[0],lt[2]                     #swap items 0 and 2
tuple_of_lists = tuple(lt)                    #convert to tuple

print(tuple_of_lists)

输出:

([3,3,3], [2,2,2], [1,1,1])

【讨论】:

    【解决方案2】:

    你为什么收到TypeError: 'tuple' object does not support item assignment

    元组在 python 中是不可变的。这意味着一旦创建/初始化,您就无法更改它们的内容。因此,元组不能位于赋值运算符的左侧,因此会出现错误。

    解决方案:

    一种可能的解决方案是更改列表,而不是更改对存储在元组中的列表的引用。考虑这个示例代码,

    a_tuple = ([1,1,1],[2,2,2],[3,3,3])
    x = 1
    y = 3
    # We'll use x-1 and y-1 for 0-based indexing
    temp = a_tuple[x-1].copy() # Keep a copy in temporary variable
    a_tuple[x-1].clear() # Empty first list
    a_tuple[x-1].extend(a_tuple[y-1]) # Fill it with second list
    a_tuple[y-1].clear() # Empty second list
    a_tuple[y-1].extend(temp) # Fill it with first list
    
    print(a_tuple)
    

    输出

    ([3, 3, 3], [2, 2, 2], [1, 1, 1])
    

    【讨论】:

    • 感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2011-09-02
    • 1970-01-01
    • 2012-01-30
    • 2017-10-30
    相关资源
    最近更新 更多