简体   繁体   English

从带有条件的Python列表中删除随机项目

[英]Remove Random Items from a list in Python with conditions

I've got this situation: 我有这种情况:

A range of days (let's say work shifts), and a different number of humans that cannot cover work shifts on specifics days. 几天的时间范围(比如说轮班),以及无法覆盖特定日期轮班的不同数量的人员。 Each day of the range has to be covered by two workers. 范围的每一天都必须由两名工人负责。

So, the newbie solution I found is that display in lists one below another the days free for each worker, with a 0 mark when they cannot work. 因此,我发现的新手解决方案是,在列表中依次显示每个工作人员免费的工作日,当他们无法工作时将其标记为0

period_of_time = range(1,10)

human_1 = [1, 3, 4, 8, "Human 1"]
human_2 = [5, 6, "Human 2"]
human_3 = [8, 9, "Human 3"]
human_4 = [2, 4, 6, "Human 4"]

humans = [human_1, human_2, human_3, human_4]

def looping_function(in_humans):
    new = []
    for d in period_of_time:
        if d not in in_humans:
            new.append(d)
        else:
            new.append(0)
    print(str(new) + " " + human_id + "\n")

for a in humans:
    in_humans = a
    human_id = a[-1]
    looping_function(in_humans)

It's works fine. 很好

[0, 2, 0, 0, 5, 6, 7, 0, 9] Human 1

[1, 2, 3, 4, 0, 0, 7, 8, 9] Human 2

[1, 2, 3, 4, 5, 6, 7, 0, 0] Human 3

[1, 0, 3, 0, 5, 0, 7, 8, 9] Human 4

And it's useful for now. 现在有用。 Considering that I working on it just for learning purposes. 考虑到我只是出于学习目的而工作。 Now I want to eliminate random items from the lists, in order to have only two humans for each day of the range. 现在,我想从列表中删除随机项目,以便该范围的每一天只有两个人。 I'm stuck here. 我被困在这里。

Soulution with usage of your code, you have to just loop through schedule and add ids 使用代码进行补充,您只需要遍历计划并添加ID

period_of_time = range(1,10)

human_1 = [1, 3, 4, 8, "Human 1"]
human_2 = [5, 6, "Human 2"]
human_3 = [8, 9, "Human 3"]
human_4 = [2, 4, 6, "Human 4"]

humans = [human_1, human_2, human_3, human_4]

def looping_function(in_humans):
    new = []
    for d in period_of_time:
        if d not in in_humans:
            new.append(d)
        else:
            new.append(0)
    print(str(new) + " " + human_id + "\n")
    return new

schedule = []
for a in humans:

    in_humans = a
    human_id = a[-1]
    schedule.append(looping_function(in_humans))

for x in range(9):
    current_day_workers = 0
    for human in schedule:
        if human[x] != 0: current_day_workers +=1
        if current_day_workers >2: human[x] = 0

print(schedule)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM