我有一本字典,其中包含某些鍵和情侶串列作為元素。我想執行以下操作:從其第二個元素(或第一個,并不重要)滿足特定條件的所有串列中洗掉每個元素(對)。我嘗試使用一段非常簡單的代碼來做到這一點,但我沒有成功,實際上我注意到了一個特定的行為:從串列中洗掉一個元素讓串列的元素 for 回圈跳過以下元素,出于某種原因(或在至少這對我來說是這樣的)。
這是一個非常簡單的例子:
# random dictionary
a = {'a': [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7]],
'b': [[2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7]]}
def f(d):
# keys in the dicitonary
for key in list(d):
# elements inthe list
for elem in d[key]:
# if the second element of the couple
# satisfies a certain criterion...
if elem[1] >= 2:
# remove that element (first occurrence) from the list
d[key].remove(elem)
return d
b = f(a)
print(b)
這是我得到的輸出:
{'a': [[1, 1], [1, 3], [1, 5], [1, 7]], 'b': [[2, 1], [2, 3], [2, 5], [2, 7]]}
這就是我想要的:
{'a': [[1, 1]], 'b': [[2, 1]]}
如何正確執行上述操作?
編輯:我知道有一些解決方法。我現在的問題是關于 for 回圈中發生的跳過事情:為什么會發生?為什么代碼不能像我認為的那樣作業?
uj5u.com熱心網友回復:
當你洗掉一個串列元素時,索引都會被調整以反映洗掉。如果您從串列的末尾作業到開頭,您將不會遇到您看到的跳過,例如
'mylist = [1,23,3,4,5,6,7,8,9]
r = range(len(mylist)-1,0,-1)
for i in r:
if mylist[i] % 2 :
mylist.pop(i)
'
uj5u.com熱心網友回復:
您可以迭代這些值(它們是串列)并在嵌套回圈中再次迭代這些串列,如果某個值不滿足您的條件,請忽略它。
# random dictionary
a = {'a': [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7]],
'b': [[2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7]]}
def f(d):
# iterate over the keys
for key in d.keys():
value_list = d[key]
# create a temporary list
temp_list = []
for elem in value_list:
# if some element doesn't match the criteria, skip it
if elem[1] >= 2:
continue
# if the condition is satisfied, add it to the temporary list
temp_list.append(elem)
# replace the key's value with the modified list
d[key] = temp_list
return d
b = f(a)
print(b)
uj5u.com熱心網友回復:
問:為什么會發生跳過?
>>> numbers = list(range(1, 6))
>>> numbers
[1, 2, 3, 4, 5]
>>> for i in numbers:
... print(f'{i=}')
i=1
i=2
i=3
i=4
i=5
上面的for回圈本質上變成了這樣:
>>> it = iter(numbers)
>>> while True:
... try:
... i = next(it)
... except StopIteration:
... break
... print(f'{i=}')
i=1
i=2
i=3
i=4
i=5
第一步是創建一個迭代器。
>>> it = iter(numbers)
您可以說它“指向”串列中的第一個元素:
[1, 2, 3, 4, 5]
^
呼叫next()回傳該元素并將“指標”向上“移動”一步。
>>> next(it)
1
it 現在指向第二個元素
[1, 2, 3, 4, 5]
^
讓我們numbers通過洗掉第一個元素來修改:
>>> numbers.pop(0)
1
>>> numbers
[2, 3, 4, 5]
我們沒有改變it它仍然指向第二個元素numbers
[2, 3, 4, 5]
^
當我們next()再次呼叫時,我們將得到3,因此2被“跳過”。
>>> next(it)
3
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422002.html
標籤:
下一篇:回圈瀏覽新舊版本的檔案
