gpt4 book ai didi

python - python中有没有一种方法可以在循环的单次迭代中循环字典中的多个键值对

转载 作者:行者123 更新时间:2023-12-01 01:41:01 25 4
gpt4 key购买 nike

我有以下示例代码,并且对 Python 中是否有一种方法可以在单个循环迭代中循环多个键值对感兴趣?如果你看到我的例子,我有一个包含四个键值对的字典,Python 中有没有办法在一次传递中循环它?

my_dict = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}

count = 1
for key, value in my_dict.items():
print('the count is {} the key is {} and the value is {}'.format(count, key, value))

count += 1
<小时/>
the count is 1 the key is key4 and the value is value4
the count is 2 the key is key3 and the value is value3
the count is 3 the key is key1 and the value is value1
the count is 4 the key is key2 and the value is value2
<小时/>

预期返回数据如下所示

iteration count 1 - key1 value1, key2 value2, key3 value3, key4 value4

最佳答案

您可以使用 list comprehensionenumerate保留当前索引。

import os

out = 'count: {}, key: {}, val: {}'
my_dict = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
os.linesep.join([out.format(c, *kv) for c, kv in enumerate(my_dict.items())])

输出:

count: 0, key: key3, val: value3
count: 1, key: key2, val: value2
count: 2, key: key1, val: value1
count: 3, key: key4, val: value4

条件示例:

要回答评论中的问题,如果您想根据条件添加或不添加项目(顺便说一句,更多 if 是可能的):

[(c, *kv) for c, kv in enumerate(my_dict.items()) if c % 0 and len(kv[1]) < 5)

同时考虑...

def do_something(c, kv):
key, value = kv
if key == 'key1':
pass # do something

# somewhere return True or False depending on your logic

[(c, *kv) for c, kv in enumerate(my_dict.items()) if do_something(c, kv)

关于python - python中有没有一种方法可以在循环的单次迭代中循环字典中的多个键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com