添加数字,然后将元组列举为元组,但它会删除外部元组
这个问题在这里已经有了答案:
使用append:
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()会有诀窍。
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()
是Python不承认()
作为一个元组,即使只有一个在它的元素。 但是,它确实承认(,)
为空元组:
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:
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.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]
[(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]
链接地址: http://www.djcxy.com/p/22565.html
上一篇: Add number, then tuple to list as a tuple, but it drops outer tuple
下一篇: Copying a sublist into a main list as objects instead of lists