python - 带有条件python的元素和下一个元素的总和
问题描述
我有一个脚本,可以生成 0,60 之间的随机数字列表,并按升序排序。
本质上,我想检查每个元素之间的差异,以及它旁边的元素是否高于 3,如果不是,我希望重新生成列表,直到条件适用。
例如:
my_list = [1, 2, 3, 4, 5]
# this would not pass
my_list = [1, 5, 9, 13, 20]
# this would pass as the difference between each element and the next is more than 3
到目前为止我的代码:
def generateList():
timeSlots = list(range(0, 60)) # generate random list
random.shuffle(timeSlots) # shuffle list
timeSlots = timeSlots[:9] # shorten list to 9 elements
timeSlots.sort() # sort list in ascending order
for cur, nxt in zip(timeSlots, timeSlots[1:]):
diff = (nxt - cur) # check difference
if diff < 3:
# HELP HERE
# regenerate timeSlots until the sum of each element and the next element is bigger than 3
return timeSlots
解决方案
你想使用all()
:
def generateList():
while True:
timeSlots = list(range(0, 60)) # generate random list
random.shuffle(timeSlots) # shuffle list
timeSlots = timeSlots[:9] # shorten list to 9 elements
timeSlots.sort() # sort list in ascending order
if all(nxt - cur > 3 for cur, nxt in zip(timeSlots, timeSlots[1:])):
return timeSlots
请注意,如果您只想选择 9 个元素,则可以使用randome.sample()
.
import random
def generate_list():
while True:
time_slots = random.sample(range(60), 9) # note this will not include 60 in the population
time_slots.sort() # sort list in ascending order
# or combine the above 2 lines as
# time_slots = sorted(random.sample(range(60), 9))
if all(nxt - cur > 3 for cur, nxt in zip(time_slots, time_slots[1:])):
return time_slots
推荐阅读
- java - 从第一个列表中查找最小元素
- batch-file - 为什么在结帐后挂钩启动记事本后 TortoiseGit Git 命令进度对话框挂起?
- android - 轻导航栏问题
- reactjs - 在反应选择选项中使用枚举
- vue.js - 如何防止事件传播到父元素?@input.stop 不起作用。(NuxtJS)
- javascript - html按钮在点击时取消选择
- java - Azure Application Insights 代理日志 Java 线程名称
- javascript - Flask-SocketIO 和 SocketIO 客户端;客户端 Emit 事件不会持续触发
- firebase-authentication - 使用 Firebase 身份验证时获取 Google 刷新令牌
- api - 从 Google Hotels 获取酒店列表