【发布时间】:2016-01-08 12:31:59
【问题描述】:
给出以下列表:
snplist = [[1786, 0.0126525], [2463, 0.0126525], [2907, 0.0126525], [3068, 0.0126525], [3086, 0.0126525], [3398, 0.0126525], [5468,0.012654], [5531,0.0127005], [5564,0.0127005], [5580,0.0127005]]
我想对列表的每个子列表中的第二个元素进行成对比较,即比较以查看来自[1786, 0.0126525] 的0.0126525 等于来自[2463, 0.0126525] 的0.0126525 等等,如果是这样,打印输出如代码所示。
使用for循环,我得到了结果:
for index, item in enumerate(snplist, 0):
if index < len(snplist)-1:
if snplist[index][1] == snplist[index+1][1]:
print snplist[index][0], snplist[index+1][0], snplist[index][1]
当使用列表索引对循环的元素进行成对比较时,由于最后一个元素,我总是遇到'index out of range' 的错误。我通过添加条件来解决这个问题
if index < len(snplist)-1:
我认为这不是最好的方法。我想知道是否有更精细的方法在 python 中对列表元素进行成对比较?
编辑:在比较浮点数时,我没有考虑过容忍度。我会认为两个具有0.001 差异的浮点数相等。
【问题讨论】:
-
您正在比较浮点数。定义“相等”。容忍度是多少?
标签: python list python-2.7