0

我有一个元组列表

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(忽略截断)?

4

3 回答 3

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
于 2013-11-09T14:09:30.667 回答
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

*除非它的错字有问题。

于 2013-11-09T14:05:43.033 回答
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 以内的值。

于 2013-11-09T14:20:19.760 回答