python遍歷集合時,如何獲取正確結果?

python遍歷一個集合時,這個集合的內容被修改了,該如何獲取這個集合的正確結果呢?

通常,更直接的做法是循環遍歷該集合的副本或創建新集合:


python遍歷集合時,如何獲取正確結果?


Python 中的 for 語句與你在 C 或 Pascal 中可能用到的有所不同。 Python 中的 for 語句並不總是對算術遞增的數值進行迭代(如同 Pascal),或是給予用戶定義迭代步驟和暫停條件的能力(如同 C),而是對任意序列進行迭代(例如列表或字符串),條目的迭代順序與它們在序列中出現的順序一致。 例如(此處英文為雙關語):

<code>>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12/<code>

在遍歷同一個集合時修改該集合的代碼可能很難獲得正確的結果。通常,更直接的做法是循環遍歷該集合的副本或創建新集合:

<code># Strategy:  Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]

# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status/<code>


分享到:


相關文章: