根据条件创建列表列表

Creating a list of lists based on a conditions

我想在所有行中循环并根据两列的条件生成列表的列表。我会删除列表 E_time[i] 和 S_time[I] 之间的数字

例如:

输入

Min = 0
Max  = 23
num_users = 100

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

输出

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]]

我试过这个代码但是

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])))

你需要 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]]

你可以用列表理解来做到这一点:

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)]

输出:

[[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]]

如果考虑速度,这比@j1-lee提出的方法快3倍。