嘗試學習python,所以我什至不知道是否有此功能。但可以說我有以下兩個字典
dict1 = {
'key1': 1
'key2': 2
'key3': 3
}
dict2 = {
'key1': 0
'key2': 2
'key3': 4
}
現在我想在兩個字典之間進行迭代,但是如果其中一個鍵的值為 0,我希望另一個字典移動到下一個字串索引。您可以假設兩個字典具有相同數量的鍵和鍵名。
基本上我想要這樣的東西:
for someKey, anotherKey in dict1, dict2:
if dict1[someKey] == 0:
#Move someKey to the next string index
#In other words move someKey from 'key1' -> 'key2' (On loop 0)
if dict2[anotherKey] == 0:
#Move anotherKey to the next string index
#In other words move someKey from 'key1' -> 'key2' (On loop 0)
正在研究 zip,但我認為它不能解決維護單獨字串索引的問題
所以示例輸出如下:
(loop 1)
1 == 0? no
0 == 0? yes
Now only move anotherKey from 'key1' to 'key2'
(loop 2)
1 == 0? no
2 == 0? no
Now here it would infinitely loop here, but I have some code
that does some dice rolling and decrements one of the
values so it guarantees one number will eventually be 0.
Just keep that in mind.
uj5u.com熱心網友回復:
我不相信有一種“pythonistic”的方式來解決它。相反,您可以嘗試使用更“演算法”的方法while:
keys1 = list(dict1.keys())
keys2 = list(dict2.keys())
i = j = 0
while i < len(keys1) and j < len(keys2):
if dict1[keys1[i]] == 0:
i = 1
if dict2[keys2[j]] == 0:
j = 1
我認為可能有另一種解決方案,但這是實用的。
uj5u.com熱心網友回復:
一種方法是使用迭代器。請參閱iter()和,此處和此處next()都記錄了 Python 內置函式以獲取一些背景資訊。
dict1 = {
'key1': 1,
'key2': 2,
'key3': 3
}
dict2 = {
'key1': 0,
'key2': 2,
'key3': 4
}
it1 = iter(dict1)
it2 = iter(dict2)
v1 = next(it1, None)
v2 = next(it2, None)
count = 0
while v1 is not None or v2 is not None:
print(f"v1, dict1[v1] {v1, dict1[v1] if v1 is not None else 'na'}, v2, dict2[v2] {v2, dict2[v2] if v2 is not None else 'na'}")
if v1 is not None and dict1[v1] == 0:
v1 = next(it1, None)
if v2 is not None and dict2[v2] == 0:
v2 = next(it2, None)
# simulate dice rolling and decrement mentioned in the question
count = 1
if count == 3:
dict1['key1'] = 0
elif count == 6:
dict2['key2'] = 0
elif count == 9:
dict1['key2'] = 0
dict2['key3'] = 0
elif count == 12:
dict1['key3'] = 0
print(f"v1, dict1[v1] {v1, dict1[v1] if v1 is not None else 'na'}, v2, dict2[v2] {v2, dict2[v2] if v2 is not None else 'na'}")
輸出:
v1, dict1[v1] ('key1', 1), v2, dict2[v2] ('key1', 0)
v1, dict1[v1] ('key1', 1), v2, dict2[v2] ('key2', 2)
v1, dict1[v1] ('key1', 1), v2, dict2[v2] ('key2', 2)
v1, dict1[v1] ('key1', 0), v2, dict2[v2] ('key2', 2)
v1, dict1[v1] ('key2', 2), v2, dict2[v2] ('key2', 2)
v1, dict1[v1] ('key2', 2), v2, dict2[v2] ('key2', 2)
v1, dict1[v1] ('key2', 2), v2, dict2[v2] ('key2', 0)
v1, dict1[v1] ('key2', 2), v2, dict2[v2] ('key3', 4)
v1, dict1[v1] ('key2', 2), v2, dict2[v2] ('key3', 4)
v1, dict1[v1] ('key2', 0), v2, dict2[v2] ('key3', 0)
v1, dict1[v1] ('key3', 3), v2, dict2[v2] (None, 'na')
v1, dict1[v1] ('key3', 3), v2, dict2[v2] (None, 'na')
v1, dict1[v1] ('key3', 0), v2, dict2[v2] (None, 'na')
v1, dict1[v1] (None, 'na'), v2, dict2[v2] (None, 'na')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451079.html
上一篇:使用dict中的鍵在pandas資料框中查找相同的“鍵”,然后將值從dict分配給資料框空列
下一篇:如何將字典資料寫入csv檔案?
