我有两个整数列表: 例如
a = [ 008, 016, 024... ]
b = [001, 002, 002, 003... 012, 016]
一致地列出增量8,而列表b更随机(例如,有时两个记录的内容)。
基本上我想要做的是产生一个连接这两个的字典,这样a [i] = b [i]< = a [i + 1]它被附加到这样的?
所以我会从b:
获得c = [ 008, 008, 008, 008 ... 016, 016]
希望这有意义吗?
答案 0 :(得分:0)
我想你正在寻找这样的东西:
>>> 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]
>>> 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]
一个非常易读的版本:
>>> 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]
答案 1 :(得分:0)
作为发电机:
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]