簡體   English   中英

Python:為什么這段代碼失敗了? 將變量分配給for循環中的自身列表

[英]Python: why does this code fail? assigning variable to list of itself in for loop

a = 'hello'
b = None
c = None
for x in [a, b, c]:
    if isinstance(x, (basestring, dict, int, float)) or x is None:
        x = [x]
a

返回“你好”,但預期['你好']。 但是,這有效:

a = 'hello'
a = [a]
a

返回['你好']

要實現這一點,首先你要了解你有兩個不同的結果,a和x(對於每個元素),以及列表[a,b,c]的引用,僅在for循環中使用,而且永遠不會更多。

為了實現目標,您可以這樣做:

a = 'hello'
b = None
c = None
lst = [a, b, c] #here I create a reference for a list containing the three references above
for i,x in enumerate(lst):
    if isinstance(x, (str,dict, int, float)) or x is None: #here I used str instead basestring
        lst[i] = [x]

print(lst[0]) #here I print the reference inside the list, that's why the value is now showed modified

['你好']

但正如我所說,如果你打印(a)它會再次顯示:

'你好'#here我打印了變量a的值,沒有修改

因為你從來沒有做過任何事。

看一下這個問題,了解更多關於引用的信息如何通過引用傳遞變量?

讓我們一次完成這一行;

a = 'hello'  # assigns 'hello' to a.
b = None  # etc...
c = None
for x in [a, b, c]:  # Creates list from the values in 'a' 'b' and 'c', then iterates over them.
    # This if statement is always True. x is always either a string, or None.
    if isinstance(x, (basestring, dict, int, float)) or x is None:
        x = [x]  # On the first iteration, sets variable to the expected ['hello']
        # After that though - it replaces it with [None]
a  # = 'hello' - you have not assigned anything to the variable except on the first line.

唯一設置為['hello']變量是x ,用None快速覆蓋。 如果您將if檢查更改為exclude or x is None並分配給a而不是x ,則可以獲得所需的結果。

值得注意的是,當你啟動for循環時會創建列表[a, b, c] 改變a bc在for循環將沒有任何效果-這樣的名單已經產生。

其他答案很棒。 我認為,概括來說,list元素是不可變的/可散列的,因此for循環返回一個副本,而不是對原始對象的引用。 我應該發現這一點,但教我編碼太長時間不睡覺!

我最終使用了這個:

def lst(x):
    if isinstance(x, (basestring, dict, int, float)) or x is None:
        x = [x]
    return x
[a, b, c] = map(lst, [a, b, c])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM