我有一个元组列表
In [142]: mylist=[(0.0, 0.0), (0.0, 0.769883), (-0.01435677, 1.7573411), (-0.3796871, -0.40361387), (-0.27704585, -1.7006601), (-0.26976547, -2.6480746), (-0.27020714, -3.0438666), (-0.2759932, -3.638946), (-0.28580084, -4.182567), (-0.29590216, -4.5594716), (-0.31486654, -5.1321993), (-0.3386181, -5.701327), (-0.37045696, -6.34038), (-0.40544215, -6.94697), (-0.45580167, -7.711907), (-0.48936173, -8.165736), (-0.52177864, -8.558438), (-0.5721365, -9.112968), (-0.6326114, -9.723627), (-0.6764244, -10.130929), (-0.7162372, -10.471702), (-0.73864824, -11.2733345), (-0.6795322, -11.688038), (-0.6065086, -12.021755), (-0.52627456, -12.4043045), (-0.42850703, -13.172687), (-0.2827803, -15.462493), (-0.25139827, -16.006815), (-0.21802832, -16.84582)]
我想检查这个元组(-0.405442, -6.94697)
是否在mylist
中。
(-0.40544215, -6.94697)
位于列表中,如下所示:
In [143]: mylist[13]
Out[143]: (-0.40544215, -6.94697)
但我的查询元组有点被截断为(-0.405442, -6.94697)
。
我如何让Python告诉我(-0.405442, -6.94697)
在mylist
中(忽略截断)?
答案 0 :(得分:1)
(-0.405442, -6.94697)
不在您的列表中。 (-0.40544215, -6.94697)
是。
如果你想检查元组是否在你的列表中,精确度为6位小数,请试试这个
(-0.405442, -6.94697) in [(round(i[0], 6), round(i[1], 6)) for i in mylist]
如果您想多次检查,最好创建一个新列表:
mynewlist = [(round(i[0], 6), round(i[1], 6)) for i in mylist]
(-0.405442, -6.94697) in mynewlist
答案 1 :(得分:0)
因为( -0.405442 , - 6.94697)与( -0.40544215 ,-6.94697)不同
>>> mylist=[(0.0, 0.0), (0.0, 0.769883), (-0.01435677, 1.7573411), (-0.3796871, -0.40361387), (-0.27704585, -1.7006601), (-0.26976547, -2.6480746), (-0.27020714, -3.0438666), (-0.2759932, -3.638946), (-0.28580084, -4.182567), (-0.29590216, -4.5594716), (-0.31486654, -5.1321993), (-0.3386181, -5.701327), (-0.37045696, -6.34038), (-0.40544215, -6.94697), (-0.45580167, -7.711907), (-0.48936173, -8.165736), (-0.52177864, -8.558438), (-0.5721365, -9.112968), (-0.6326114, -9.723627), (-0.6764244, -10.130929), (-0.7162372, -10.471702), (-0.73864824, -11.2733345), (-0.6795322, -11.688038), (-0.6065086, -12.021755), (-0.52627456, -12.4043045), (-0.42850703, -13.172687), (-0.2827803, -15.462493), (-0.25139827, -16.006815), (-0.21802832, -16.84582)]
>>> (-0.40544215, -6.94697) in mylist
True
*除非有问题。
答案 2 :(得分:0)
如果您想使用理解找到近似匹配,您可以通过检查您想要的数字的绝对值减去所找到的数量是否小于某个限制来检查该数字是否“足够接近”您想要的值,例如;
>>> [(x,y) for (x,y) in mylist if abs(-0.405442-x)<0.001 and abs(-6.94697-y)<0.001]
[(-0.40544215, -6.94697)]
...会找到所需值的0.001以内的值。