我已经接近搞清楚这个问题,但我特别挂了一件事。我试图将一对列表中的元素配对/压缩在一起,然后检查哪个值更大。我无法弄清楚如何在不重复值的情况下配对这些元素。
[35,10,5,3,1,26,15]
我不想要:
[35,10], [10,5]
我想要:
[35,10], [5,3]
这是我的代码:
def queue_time(customers, n):
time_left = 0
max_val = max(customers[:n])
total_time = int(max_val)
other_customers = list(customers)
other_customers.remove(max_val)
for idx, el in enumerate(other_customers):
if max_val > 0:
nxt_till_times = other_customers[idx:idx+n-1]
max_other_tills = max(nxt_till_times)
max_val -= max_other_tills
print nxt_till_times
elif max_val == 0:
max_val = max(customers[idx:idx+n])
total_time += max_val
elif max_val < 0:
time_left = [-1*(max_val)]
others_still = time_left + customers[idx+1:]
max_val = max(others_still[:n])
total_time += max_val
#print total_time
return total_time
queue_time([35,10,5,3,1,26,15], 3)
答案 0 :(得分:1)
更简单:
>>> l = [35,10,5,3,1,26,15]
>>> [l[i:i+2] for i in range(0, len(l)-1, 2)]
[[35, 10], [5, 3], [1, 26]]
这将切断列表中任何奇数编号的元素。
答案 1 :(得分:0)
l = [35,10,5,3,1,26,15]
g = (i for i in l)
output = [(next(g), next(g)) for i in range(len(l)//2)]
g
是一个生成器。这对奇数长度列表的最后一个元素没有任何作用。该元素位于next(g)