检查数字是否在列表范围内

时间:2014-12-14 12:26:15

标签: python

我有一个问题,我不知道如何解决 基本上我有一个这样的名字列表:

names = ['Andrea','21','Sophie',16]

和一个与这个不一样的数字列表:

details = ['21.43222','100.2334'] ##first time you run the program
details = ['23.53422','103.2334'] ##second time you run the program

我想要的是即使第二次的结果与第一次的结果不同,它也会链接到同一个人。

我的意思是即使在我的最终名单中Andrea与数字21.43222相关联,即使我们第二次运行程序并且结果在+ -5范围内(在这种情况下在16.43222和26.43222之间)这个数字也与安德里亚有关。 感谢

1 个答案:

答案 0 :(得分:0)

首先,使用一个更连贯的数据结构来保存信息:

names = ['Andrea','21','Sophie',16]
people = zip(names[::2], names[1::2])
# people is now: [('Andrea', '21'), ('Sophie', 16)]

现在,如果您尝试将每个细节与最亲近的人联系起来:

# now test which who is closest to the detail (if that's what you meant to do)
map(lambda detail: (detail, min(people, key=lambda x: abs(float(x[1]) - float(detail)))), details)
# explanation: returns a tuple: (detail, person with minimal distance from detail)