我有两个整数列表:例如
a = [ 008, 016, 024... ]
b = [001, 002, 002, 003... 012, 016]
列表 a 一致地递增 8,而列表 b 更随机(例如,有时两个记录的整数)。
基本上我想要做的是产生一个连接这两者的字典,这样 a[i] = b[i] <= a[i+1] 它被附加到这样的?
所以我会从 b 得到:
c = [ 008, 008, 008, 008 ... 016, 016]
希望这是有道理的?
I guess you're looking for something like this:
>>> a = [ 8, 16, 24, 32 ]
>>> b = [1, 2, 2, 3, 12, 16]
>>> [a[0] if a[0] < x and [a.pop(0)] else a[0] for x in b ]
[8, 8, 8, 8, 16, 16]
Using collections.deque
:
>>> from collections import deque
>>> d = deque(a)
>>> [d[0] if d[0] < x and [d.popleft()] else d[0] for x in b ]
[8, 8, 8, 8, 16, 16]
A much read-able version:
>>> it = iter(a)
>>> prev = next(it)
>>> result = []
for x in b:
if x <= prev:
result.append(prev)
else:
prev = next(it)
result.append(prev)
...
>>> result
[8, 8, 8, 8, 16, 16]
作为生成器:
def make_c(a, b):
a_idx = 0
for elt in b:
# while loop can be replaced with "if"
# as long as jumps in b never skip elements in a
while elt > a[a_idx]:
a_idx += 1
yield a[a_idx]