我有两个元组列表如下:
actions = [(2, 1), (1, 0), 'lift 4', (2, 1), 'down 2', (1, 2), 'lift 4', 'down 2']
costs = [(2, 1, 3), (1, 0, 3), (2, 1, 3), (1, 2, 3)]
这是我想要的最终结果:
final_list = [(2, 1, 3), (1, 0, 3),'lift 4', (2, 1, 3),'down 2', (1, 2, 3),'lift 4','down 2' ]
我在这做什么..元组的前两个元素对应于(x,y)坐标..然后字符串是"动作"我接受那个坐标。 现在,在"成本" list ..基于运动(对角线运动成本为3,而线性运动成本为2),我将成本附加到元组,忽略了动作。
如何合并这两个列表,以便我得到结果" final_list"
答案 0 :(得分:2)
一种解决方案是将costs
简单地视为查找表。第一,
将其转换为方便的dict
:
cost_dict = {i[:2] : i for i in costs}
{(1, 2): (1, 2, 3), (1, 0): (1, 0, 3), (2, 1): (2, 1, 3)}
然后有条件地转换actions
中的值:
final_list = [cost_dict[i] if isinstance(i, tuple) else i for i in actions]
[(2, 1, 3), (1, 0, 3), 'lift 4', (2, 1, 3), 'down 2', (1, 2, 3), 'lift 4', 'down 2']
答案 1 :(得分:1)
相当直接的方法:
costs.reverse()
final_list = []
for action in actions:
if isinstance(action, tuple):
# assume that costs in the order as actions
final_list.append(costs.pop())
else:
final_list.append(action)
final_list
答案 2 :(得分:1)
首先创建一个字典以将操作映射到成本:
actions = [(2, 1), (1, 0), 'lift 4', (2, 1), 'down 2', (1, 2), 'lift 4', 'down 2']
costs = [(2, 1, 3), (1, 0, 3), (2, 1, 3), (1, 2, 3)]
cost_map = {cost[:2] : cost for cost in costs}
现在,您可以使用dict.get()
和默认值来处理操作列表:
final_list = [cost_map.get(action, action) for action in actions]
>>> final_list
[(2, 1, 3), (1, 0, 3), 'lift 4', (2, 1, 3), 'down 2', (1, 2, 3), 'lift 4', 'down 2']
答案 3 :(得分:0)
假设元组actions
和costs
列表的位置已映射并且按顺序排列,为了获得所需的结果,您可以创建一个中间列表来存储{{1}的索引tuple
列表中的对象:
actions
然后根据以前的索引将值从>>> actions = [(2, 1), (1, 0), 'lift 4', (2, 1), 'down 2', (1, 2), 'lift 4', 'down 2']
>>> costs = [(2, 1, 3), (1, 0, 3), (2, 1, 3), (1, 2, 3)]
>>> tuple_position = [i for i, a in enumerate(actions) if isinstance(a, tuple)]
>>> tuple_position
[0, 1, 3, 5]
列表更新到costs
列表:
actions