AAA
AAA

Reputation: 157

Creating a list of lists based on a conditions

I would like to loop in all rows and generate a list of a list based on a condition from two columns. I would remove the numbers between E_time[i] & S_time[I] in the list

for example :

Input

Min = 0
Max  = 23
num_users = 100

S_time = [6,5,10]
E_time = [18,19,17]

Output

time_slots_customer = [[0,1,2,3,4,5,19,20,21,22,23],
                       [0,1,2,3,4,20,21,22,23],
                       [0,1,2,3,4,5,6,7,8,9,18,19,20,21,22,23]]

I tried this code but

time_slots_customers = []

for i in num_users:
    if E_time[i] > S_time[i]:
        time_slots_customers.append(list(range(S_time[i], E_time[i])))

Upvotes: 1

Views: 551

Answers (2)

j1-lee
j1-lee

Reputation: 13929

You would need zip:

time_min = 0
time_max = 23

start_times = [6,5,10]
end_times = [18,19,17]

time_slots_customer = []
for s, e in zip(start_times, end_times):
    time_slots_customer.append([t for t in range(time_min, time_max+1) if t not in range(s, e+1)])
# Alternatively:
#   time_slots_customer.append([t for t in range(time_min, time_max+1) if not s <= t <= e])

print(time_slots_customer)
# [[0, 1, 2, 3, 4, 5, 19, 20, 21, 22, 23], [0, 1, 2, 3, 4, 20, 21, 22, 23], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 18, 19, 20, 21, 22, 23]]

Upvotes: 2

Nin17
Nin17

Reputation: 3472

You can do this with list comprehension:

Min = 0
Max  = 23
num_users = 100

S_time = [6,5,10]
E_time = [18,19,17]
[[k for k in range(Min, Max+1) if (k<i or k>j)] for (i, j) in zip(S_time, E_time)]

Output:

[[0, 1, 2, 3, 4, 5, 19, 20, 21, 22, 23],
 [0, 1, 2, 3, 4, 20, 21, 22, 23],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 18, 19, 20, 21, 22, 23]]

This is 3 times faster than the method proposed by @j1-lee if speed is a consideration.enter image description here

Upvotes: 3

Related Questions