一、問題描述
在使用Python的時候,有時候會遇到這樣的問題:name ‘list’ is not defined,這個問題通常發生在使用Python中的list(列表)時,尤其是在使用互動式環境(如Python IDLE)時。這個問題的出現,會導致Python中的list無法正常使用,進而影響代碼的功能。
二、問題原因
在Python中,每一個模塊都有自己的命名空間,這個命名空間是獨立的。如果在一個模塊中定義了一個變數或者函數,那麼這個變數或者函數只能在該模塊中使用。如果需要在其他模塊中使用該變數或者函數,需要使用import語句將該模塊引入到當前模塊中。
當我們在使用Python互動式環境(如Python IDLE)時,互動式環境會將我們輸入的命令和代碼分別封裝為兩個模塊,分別為__main__和__console__。這就意味著,如果我們在互動式環境中直接使用list,那麼實際上我們是在__main__模塊中使用,而不是在Python內置的list模塊中使用。由於__main__模塊默認不會引入內置的list模塊,所以就會導致name ‘list’ is not defined的問題。
三、解決方法
1. 在互動式環境中使用from __future__ import 語句
在互動式環境中,我們可以使用from __future__ import語句,來將當前模塊的語法轉換為Python 3.x中的語法。其中,from __future__ import print_function可以將當前模塊中的print語句轉換為Python 3.x中的print函數,而from __future__ import unicode_literals可以讓當前模塊中的字元串默認使用Unicode編碼。
Python 2.7.17 (default, Nov 7 2019, 10:07:09)
[GCC 7.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import print_function
>>> from __future__ import unicode_literals
>>> lst = [1, 2, 3, 4]
>>> print(lst)
[1, 2, 3, 4]
2. 引入內置的list模塊
我們可以使用import語句,將內置的list模塊引入到當前模塊中。這樣,我們就可以在當前模塊中正常使用list了。
>>> import __builtin__
>>> lst = [1, 2, 3, 4]
>>> __builtin__.list(lst)
[1, 2, 3, 4]
3. 定義當前模塊中的list函數
我們可以在當前模塊中定義一個list函數,實現類似於內置的list函數的功能。這樣,我們就可以在當前模塊中正常使用list了。
>>> def list(iterable):
... if iterable is None:
... return []
... if hasattr(iterable, '__iter__'):
... return [i for i in iterable]
... else:
... return [iterable]
...
>>> lst = [1, 2, 3, 4]
>>> list(lst)
[1, 2, 3, 4]
四、總結
在使用Python中的list時,如果出現name ‘list’ is not defined問題,通常是由於當前模塊沒有引入內置的list模塊,或者當前模塊命名空間中沒有定義list函數。針對這個問題,我們可以使用from __future__ import語句,將當前模塊的語法轉換為Python 3.x中的語法。或者使用import語句,將內置的list模塊引入到當前模塊中。還可以在當前模塊中定義一個list函數,實現類似於內置的list函數的功能。通過這些方法,我們就可以在當前模塊中正常使用list了。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/287069.html