提问人:therickster 提问时间:7/26/2023 更新时间:7/26/2023 访问量:29
(蟒蛇)两个不均匀嵌套的对象列表的差异,按元素划分
(Python) Difference of two unevenly nested lists of objects, elementwise
问:
我有两个不均匀嵌套的数字列表,
lst1 = [0.1, [0.2, 0.3], [0.4, 0.5, 0.6, [0.7, 0.8], 0.9]]
和
lst2 = [0.1, [0.1, 0.1], [0.1, 0.1, 0.1, [0.1, 0.1], 0.1]]
我想采取差异,从元素上讲,获得lst1 - lst2
lst1 - lst2 = [0.1, [0.1, 0.2], [0.3, 0.4, 0.5, [0.6, 0.7], 0.8]]
.
答:
1赞
chepner
7/26/2023
#1
只要保证两个列表具有相同的形状,就可以递归减去相应的元素。
def diff(lst1, lst2):
return [x - y if instance(x, float) else diff(x, y) for x, y in zip(lst1, lst2)]
1赞
Maria K
7/26/2023
#2
你可以递归地做到这一点:如果当前元素对是列表,则遍历列表,否则定期减去:
def subtract(entity1, entity2):
result = []
if isinstance(entity1, list):
assert isinstance(entity2, list)
for el1, el2 in zip(entity1, entity2):
result.append(subtract(el1, el2))
else:
result = entity1 - entity2
return result
lst1 = [0.1, [0.2, 0.3], [0.4, 0.5, 0.6, [0.7, 0.8], 0.9]]
lst2 = [0.1, [0.1, 0.1], [0.1, 0.1, 0.1, [0.1, 0.1], 0.1]]
subtract(lst1, lst2)
输出:
[0.0,
[0.1, 0.19999999999999998],
[0.30000000000000004, 0.4, 0.5, [0.6, 0.7000000000000001], 0.8]]
上一个:R 中的嵌套列表的平均值
评论