首页 > 解决方案 > 如何仅在 Python 的嵌套循环中迭代列表一次

问题描述

我打算向许多号码发送消息,但这是我的代码和问题(代码更短,所需的行在这里):

msg = 'test message'
phone_numbers = ['+989111111111', '+989111111112', '+989111111113', '+989111111114']
hours = range(0, 25)
minutes = range(0, 60)
for phone_number in phone_numbers:
    for hour in hours:
        for minute in minutes:
            sndmsg(phone_number, msg, hour, minute)

我知道我的方法不正确,因为这是输出,但我不知道如何解决这个问题。谷歌搜索这对我没有帮助。

输出:

test message to +989111111111 will be sent on 0 0
test message to +989111111111 will be sent on 0 1
test message to +989111111111 will be sent on 0 2
...
test message to +989111111112 will be sent on 0 0
test message to +989111111112 will be sent on 0 1
test message to +989111111112 will be sent on 0 2

我想要的输出是这样的:

test message to +989111111111 will be sent on 0 0
test message to +989111111112 will be sent on 0 1
test message to +989111111113 will be sent on 0 3

我想像上面的输出一样在每分钟内向每个号码发送消息,我怎样才能做到这一点?

标签: pythonpython-3.xlistloops

解决方案


尝试使用生成器来计算小时和分钟,然后使用电话号码进行压缩:

msg = 'test message'
phone_numbers = ['+989111111111', '+989111111112', '+989111111113', '+989111111114']

def gen_hour_min():
    hours = range(0, 25)
    for hour in hours:
        minutes = range(0, 60)
        for minute in minutes:
            yield hour, minute

for phone_number, hour_min in zip(phone_numbers, gen_hour_min()):
    hour, minute = hour_min
    print(phone_number, hour, minute)

推荐阅读