【问题标题】:How can I iterate through a list within the dictionary and run the command for each index?如何遍历字典中的列表并为每个索引运行命令?
【发布时间】:2021-03-25 17:49:13
【问题描述】:

我有一个字典,其中索引号作为键,值中包含 5 个整数的列表。我想运行一个 set 命令,以便为所有索引号一一设置列表的第 0 个元素的速度,然后根据索引对其他元素重复相同的操作。我通过在列表元素的范围内运行它来达到同样的效果。任何人都可以帮助实现这一目标吗? 以下是字典

dict = {0: [13440, 7000, 8800, 11000, 15000], 1: [14310, 7000, 8800, 11000, 15000], 2: [13410, 7000, 8800, 11000, 15000], 3: [14130, 7000, 8800, 11000, 15000], 4: [13380, 7000, 8800, 11000, 15000], 5: [14280, 7000, 8800, 11000, 15000], 6: [13500, 7000, 8800, 11000, 15000], 7: [14190, 7000, 8800, 11000, 15000], 8: [9150, 3000, 3800, 4800, 6000, 8500], 9: [8670, 3000, 3800, 4800, 6000, 8500]}

for index, speeds in dict.items():
    for i in range(len(speeds)):
        cmd = 'set %d speed %s' % (index, speeds[i])
        print(cmd)

我希望 cmd 运行索引 0,1,2,3....8,9 的列表的第 0 个元素。同样,它应该为所有索引的第一个元素运行,依此类推。所以,基本上应该先设置每个索引号的第一速度,然后设置每个索引号的第二速度,依此类推。希望我的问题很清楚。 我得到的当前输出是这个

set 0 speed 13440
set 0 speed 7000
set 0 speed 8800
set 0 speed 11000
set 0 speed 15000
set 1 speed 14310
.
.
. 
set 9 speed 8500

我期待类似的东西

set 0 speed 13440
set 1 speed 14310
set 2 speed 13410
set 3 speed 14130
.
.
and so on

【问题讨论】:

  • 您发布的代码具体有什么问题?
  • 附加了我得到的输出和所需的输出@kaya3

标签: python


【解决方案1】:

您可以确定dict 中列表的最大长度,并在外循环中遍历每个索引,同时在内循环中遍历dict 的键。注意长度小于最大值的列表。

编辑:使用time.sleep 在速度变化之间添加睡眠。更改了变量名称以更具描述性。

import time

dict = {0: [13440, 7000, 8800, 11000, 15000], 1: [14310, 7000, 8800, 11000, 15000], 2: [13410, 7000, 8800, 11000, 15000], 3: [14130, 7000, 8800, 11000, 15000], 4: [13380, 7000, 8800, 11000, 15000], 5: [14280, 7000, 8800, 11000, 15000], 6: [13500, 7000, 8800, 11000, 15000], 7: [14190, 7000, 8800, 11000, 15000], 8: [9150, 3000, 3800, 4800, 6000, 8500], 9: [8670, 3000, 3800, 4800, 6000, 8500]}

# The maximum length of dict's lists of speeds
max_speed_count = max(len(lst) for lst in dict.values())

for speed_index in range(max_speed_count):
    for fan_index in dict:
        # If one of the lists has smaller length, catch the error and continue
        try:
            speed = dict[fan_index][speed_index]
        except IndexError:
            continue
        
        cmd = 'fan_set %d speed %s' % (fan_index, speed)
        print(cmd)

    # Sleep for a minute between speed changes
    time.sleep(60)

【讨论】:

  • 这很有帮助。在此之后还有一个步骤,但我不知道如何实现。因此,在使用列表的第 0 个元素为所有索引设置风扇速度后,我需要引入 1 分钟的延迟,然后为所有索引运行第一个元素,依此类推。 @Božo Stojković 有可能吗?
  • 您只需要import time 并使用time.sleep 作为参数,它需要几秒钟才能进入睡眠状态。 @Jayashri
  • 虽然代码完全符合您的描述。也许你没有正确复制它?注意缩进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多