首页 > 解决方案 > 带有条件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

标签: pythonpython-3.xlistmathrandom

解决方案


你想使用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

推荐阅读