如何使用python中的映射函数将项目从一个列表减去另一个列表
Posted
技术标签:
【中文标题】如何使用python中的映射函数将项目从一个列表减去另一个列表【英文标题】:How to subtract items from one list to another usinp zip funcitons in python 【发布时间】:2021-04-25 01:38:58 【问题描述】:伙计们,我有以下代码:
def disFn(a, b):
return[[abs(m-n) for o,p in zip(m,n)] for m,n in zip(a[1],b[1])]
但它不起作用..我需要做的是下面列表中的 ech 元组返回元组中每个值之间的差异,例如......我想得到以下元组
( abs(0.0 - 8.708170812), abs(8.708170812 - 0.0), abs(4.088197921 - 10.518235207), abs(11.366319879999999 - 7.668395996), abs(12.638763287 - 10.522399903), abs(11.078233943 - 7.302185059), abs(10.025102839 - 6.417022705), abs(8.415467337 - 6.146172005), abs(8.194840093 - 10.448354985), abs(13.455056175000001 -5.149291993)),
data = [('highway_bost174', [0.0, 8.708170812, 4.088197921, 11.366319879999999, 12.638763287, 11.078233943, 10.025102839, 8.415467337, 8.194840093, 13.455056175000001]),
('ibis_142', [8.708170812, 0.0, 10.518235207, 7.668395996, 10.522399903, 7.302185059, 6.417022705, 6.146172005, 10.448354985, 5.149291993]),
('street_par88', [4.088197921, 10.518235207, 0.0, 11.135904053, 11.472831274, 10.691568116, 9.663827636, 10.659660884000001, 9.392413013999999, 12.586018896]),
('opencountry_241', [11.366319879999999, 7.668395996, 11.135904053, 0.0, 13.314941407, 2.754882813, 3.998626709, 9.028326501, 12.145703089000001, 8.675354002999999]),
('waterfall23', [12.638763287, 10.522399903, 11.472831274, 13.314941407, 0.0, 12.665527344000001, 11.406341552, 12.6048929, 11.43774673, 8.79888916]),
('field26', [11.078233943, 7.302185059, 10.691568116, 2.754882813, 12.665527344000001, 0.0, 3.349212646, 8.966176812, 11.827669236000002, 8.203674316]),
('mountain_030', [10.025102839, 6.417022705, 9.663827636, 3.998626709, 11.406341552, 3.349212646, 0.0, 8.78585096, 11.994283939999999, 7.7325744620000005]),
('horse_081', [8.415467337, 6.146172005, 10.659660884000001, 9.028326501, 12.6048929, 8.966176812, 8.78585096, 0.0, 8.054160893999999, 11.093641082000001]),
('bison_052', [8.194840093, 10.448354985, 9.392413013999999, 12.145703089000001, 11.43774673, 11.827669236000002, 11.994283939999999, 8.054160893999999, 0.0, 12.869559482]),
('ibis_040', [13.455056175000001, 5.149291993, 12.586018896, 8.675354002999999, 8.79888916, 8.203674316, 7.7325744620000005, 11.093641082000001, 12.869559482, 0.0])]
【问题讨论】:
【参考方案1】:def disFn(a, b):
return[abs(m-n) for m,n in zip(a[1],b[1])]
print(disFn(data[0], data[1]))
输出:
[8.708170812, 8.708170812, 6.430037286, 3.697923883999999, 2.1163633839999996, 3.7760488840000006, 3.6080801340000006, 2.2692953320000004, 2.253514892, 8.305764182]
为什么嵌套列表理解,只有一层列表理解可以正常工作。
也许我不明白你的意思?
【讨论】:
【参考方案2】:如果我正确理解您的问题,您根本不需要使用 zip()。这应该会给你你想要的结果:
tuple([abs(values[0] - values[1]) for key, values in data])
【讨论】:
以上是关于如何使用python中的映射函数将项目从一个列表减去另一个列表的主要内容,如果未能解决你的问题,请参考以下文章
如何将列表中的每个项目与Python中另一个列表的所有值一起使用[重复]