python - 如何仅在 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
我想像上面的输出一样在每分钟内向每个号码发送消息,我怎样才能做到这一点?
解决方案
尝试使用生成器来计算小时和分钟,然后使用电话号码进行压缩:
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)
推荐阅读
- multithreading - 有比赛条件是可以接受的吗?
- mysql - 在触发器中使用 join in update 命令
- typescript - 物业类型取决于其他物业的类型
- excel - 使用列表框显示 Excel 文件中的 2 列
- java - 使用 java -jar 命令时,Java 似乎已过时
- java - 在java中清除arraylist
- reactjs - React-intl 解析语言环境文件中的 json 数组
- python - 替换数据框列中多个字符串的函数 - “TypeError:预期的字符串或类似字节的对象”
- php - 从具有对象的 PHP 数组中获取 MAX/MIN
- hashicorp-vault - 在 HashiCorp 中创建命名空间时出现不支持的路径错误