在看到以下 Python 程序的输出后,我有点困惑:
t = [0,1,2]
t[2:].append(t[0])
print(t)
输出:
[0,1,2]
这里,我选取了一个列表 [0,1,2]
。为什么输出是 [0,1,2],而不是 [0,1,0]?请有人帮助我消除我的疑问。
答案 0 :(得分:3)
这是因为 t[2:]
创建了另一个列表,并且您要附加到该列表,但最终您打印的是原始列表 t
给一些光:
t
是一个列表对象,当您执行 t[2:]
时,您正在创建一个基于第一个的新列表对象。然后,您向这个新对象附加一个值,由于您没有将该新对象存储在任何变量中,因此该对象丢失了。
最后,您只需打印未更改的原始列表。
试试这个:
new_t = t[2:] # New object with your slice
new_t.append(t[0]) # Appending a value of your old list to this new created list
print(new_t) # Printing the new list
答案 1 :(得分:0)
这行代码,什么都不做:
t[2:].append(t[0])
对于期望的结果使用:
t = [0,1,2]
t2 = t[:2] # we only need 1st and 2nd value from t
t2.append(t[0]) # append 1st value of t in the last of t2 to generate the desired list
print(t2) # print t2 (the desired list)
或
t = [0,1,2]
t[-1] = t[0] # update the last element of list, same as first element
print(t) # print updated list having desired answer