简体   繁体   中英

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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