Add number, then tuple to list as a tuple, but it drops outer tuple
This question already has an answer here:
使用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)
Changing it to append() does the trick.
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 adds the data structure as is to the end of the list, extend extracts the iterables. To understand it better append vs. extend
You can do it using both extend()
and append()
. The problem with your code using extend()
is that Python does not recognize ()
as a tuple, even if there is only one element in it. However, it does recognize (,)
as an empty tuple:
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)
The other way, as Vedang Mehta has said, is to use 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)
Both will give you the result of:
[(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/22566.html
上一篇: 保存程序运行时对列表所做的更改