社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在两个python字典之间迭代,并能够分别“递增”到下一个字符串索引

Chonga • 4 年前 • 2226 次点击  

试图学习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. 
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131263
文章 [ 3 ]  |  最新文章 4 年前