使用索引进行列表操作

JK2*_*018 0 python

我有两个清单。

名单A:

A = ["apple","cherry","pear","mango","banana","grape","kiwi","orange","pineapple"]
Run Code Online (Sandbox Code Playgroud)

清单B:

B = [{"offset":0, "xx":789},{"offset":3, "xx":921},{"offset":6, "xx":89}]
Run Code Online (Sandbox Code Playgroud)

这个想法是使用 B 中每个项目的偏移量作为索引偏移量来设置结果数组中的 xx 值。例如,这将是预期的结果:

C=[
{"fruit":"apple","xx":789},
{"fruit":"cherry","xx":789},
{"fruit":"pear","xx":789},
{"fruit":"mango","xx":921},
{"fruit":"banana","xx":921},
{"fruit":"grape","xx":921},
{"fruit":"kiwi","xx":89},
{"fruit":"orange","xx":89},
{"fruit":"pineapple","xx":89},
]
Run Code Online (Sandbox Code Playgroud)

例如,B[0] 的“偏移量”为 0。这意味着索引 >= 0 的 C 将具有 B[0]['xx'] 的“xx”值。然后我们的 B[0]['offset'] 为 3,它将为索引 >= 3 的 C 项设置新的“xx”值,依此类推。

我能够使用数据框和 pandas 获得类似的结果。但由于 pandas 库相当重,所以要求我不使用 pandas 来完成它。

moz*_*way 6

使用简单的循环怎么样?

# rework B in a better format
dic = {d['offset']:d['xx']  for d in B}
# {0: 789, 3: 921, 6: 89}

C = []

v = None
for i, a in enumerate(A):
    v = dic.get(i, v) # if we reached a threshold, update the value
    C.append({'fruit':a, 'xx': v})

print(C)
Run Code Online (Sandbox Code Playgroud)

输出:

[{'fruit': 'apple', 'xx': 789},
 {'fruit': 'cherry', 'xx': 789},
 {'fruit': 'pear', 'xx': 789},
 {'fruit': 'mango', 'xx': 921},
 {'fruit': 'banana', 'xx': 921},
 {'fruit': 'grape', 'xx': 921},
 {'fruit': 'kiwi', 'xx': 89},
 {'fruit': 'orange', 'xx': 89},
 {'fruit': 'pineapple', 'xx': 89}]
Run Code Online (Sandbox Code Playgroud)