1. 程式人生 > >python3中列表方法無返回值問題

python3中列表方法無返回值問題

python程式設計中遇到過列表操作無返回值的情況,如今趁著溫習,記錄一下。

簡單的來說除了count、index、copy、pop外其他的方法都沒有返回值,而且特別強調的是,copy返回的是該列表的值(若將該返回值複製給另外一個變數,則效果是對原列表的一個淺複製,即新的變數完成了對原列表的引用。python3中已經列表和字典的copy方法已經不存在淺複製的問題了,通過實踐驗證,採用copy得到的副本和原件之間不存在相互影響的問題),pop則是唯一的一個既原地修改原列表又能返回值的方法。

列表和字典的淺複製到底是什麼意思呢?比如說

>>> x=[1,2,[1,2,3]]
>>> y=x.copy()
>>> id(x)
2397212213640
>>> id(y)
2397212127560
>>> x is y
False
>>> x[0] is y[0]
True
>>> x[1] is y[1]
True
>>> x[2] is y[2]
True
至此看出了列表和字典作為容器的特性,雖然淺複製後x、不是同一個物件,但是容器內的物件是相同的
>>> y[2].append(100)
>>> y
[1, 2, [1, 2, 3, 100]]
>>> x
[1, 2, [1, 2, 3, 100]]

 也就是說,淺複製雖然得到了新的容器,但是容器內的物件則還是原容器內的物件,也就是說新容器內的物件實際上是原容器內對應物件的引用。若對該物件是不可變物件則無影響,若該物件也是一個容器,那麼對這個物件的改變則是會擴散到的,從而影響到源容器內的對應物件。

>>> a=[1,2,3]
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', 
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__',
 '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy',
 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> a.append(4)     #執行完螢幕上啥也沒有,說明沒有返回值
>>> a.extend('safa')     #執行完螢幕上啥也沒有,說明沒有返回值
>>> a.count('a')      #有返回值,表示物件最為列表成員出現的次數,即通過一次索引即可找到該元素,這種元素出現的次數
2
>>> a.index(3)       #返回列表中第一個該元素出現的索引位置
2
>>> a.index('a')
5
>>> a.index('a',6)    #也可指定查詢範圍,結束位置可省
7
>>> a.insert(3,"nihao')
  File "<stdin>", line 1
    a.insert(3,"nihao')
                      ^
SyntaxError: EOL while scanning string literal
>>> a.insert(3,"nihao")    #執行完螢幕上啥也沒有,說明沒有返回值
>>> a.remove('a')      #執行完螢幕上啥也沒有,說明沒有返回值
>>> a.reverse()      #執行完螢幕上啥也沒有,說明沒有返回值
>>> a.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
>>> a
['a', 'f', 's', 4, 'nihao', 3, 2, 1]
>>> a.pop('nihao')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> a.remove('nihao')
>>> a.pop(0)   返回並刪除指定位置的元素,預設則預設為列表尾部
'a'
>>> a.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
>>> a.clear()     #執行完螢幕上啥也沒有,說明沒有返回值