本问题已经有最佳答案,请猛点这里访问。
我试图添加一个(number, (tuple))的元组,但它删除了外部元组。
我如何改变代码使l1看起来像L2?它似乎要删除外部元组并将其转换为列表元素?我该怎么阻止呢?更好的是,为什么会发生这种情况?
1 2 3 4 5 6 7 8 9 10 | l1 = [] t1 = (1.0 , (2.0,3.0)) l1.extend((t1)) t2 = (4.0 , (5.0,6.0)) l1.extend(t2) print(l1) l2 = [(1.0, (2.0,3.0)), (4.0, (5.0,6.0))] print(l2) |
l1出来为[1.0、(2.0,3.0),4.0 (5.0,6.0)]
l2出来[(1.0 (2.0,3.0),(4.0 (5.0,6.0)))
使用附加:
1 2 3 4 5 6 7 8 9 10 | l1 = [] t1 = (1.0 , (2.0,3.0)) l1.append((t1)) t2 = (4.0 , (5.0,6.0)) l1.append(t2) print(l1) l2 = [(1.0, (2.0,3.0)), (4.0, (5.0,6.0))] print(l2) |
将其更改为append()就可以了。
1 2 3 4 5 6 7 8 9 10 | l1 = [] t1 = (1.0 , (2.0,3.0)) l1.append((t1)) t2 = (4.0 , (5.0,6.0)) l1.append(t2) print(l1) l2 = [(1.0, (2.0,3.0)), (4.0, (5.0,6.0))] print(l2) |
l1 - [(1.0, (2.0, 3.0), (4.0, (5.0, 6.0)]
l2 - [(1.0, (2.0, 3.0), (4.0, (5.0, 6.0)]
Append将数据结构添加到列表的末尾,extend提取迭代器。为了更好地理解append和extend
您可以同时使用
1 2 3 4 5 6 7 8 9 10 11 12 | l1 = [] t1 = (1.0 , (2.0,3.0)) # Note the extra comma l1.extend((t1,)) t2 = (4.0 , (5.0,6.0)) # Note the extra enclosing parentheses and comma l1.extend((t2,)) print(l1) l2 = [(1.0, (2.0,3.0)), (4.0, (5.0,6.0))] print(l2) |
另一种方法,正如Vedang Mehta所说,是使用append:
1 2 3 4 5 6 7 8 9 10 | l1 = [] t1 = (1.0 , (2.0,3.0)) l1.append(t1) t2 = (4.0 , (5.0,6.0)) l1.append(t2) print(l1) l2 = [(1.0, (2.0,3.0)), (4.0, (5.0,6.0))] print(l2) |
两者都会给你以下结果:
1 2 | [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))] [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))] |