【问题标题】:Pairwise comparison of elements in a list python列表python中元素的成对比较
【发布时间】: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


【解决方案1】:

你可以zipsnplist除了第一个元素之外的相同列表,并进行比较,像这样

for l1, l2 in zip(snplist, snplist[1:]):
    if l1[1] == l2[1]:
      print l1[0], l2[0], l1[1]

由于您要比较浮点数,我建议您使用 Python 3.5 中的 math.isclose 函数,如下所示

def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
    return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

因为你想有 0.001 的容差,你可以像这样进行比较

if is_close(l1[1], l2[1], 0.001):

【讨论】:

  • hmm,OP用的是Python2.7,math.is_close怎么导入?
  • @timgeb 是一个简单的两行。我希望他可以复制粘贴并使用它:-)
【解决方案2】:

我建议您为此使用izip 来创建项目-邻居对的生成器。抛开比较浮点的问题不谈,代码如下所示:

>>> from itertools import izip
>>> lst = [[1,2], [3,4], [5,4], [7,8], [9,10], [11, 10]]
>>> for item, next in izip(lst, lst[1:]):
...     if item[1] == next[1]:
...         print item[0], next[0], item[1]
... 
3 5 4
9 11 10

记住在比较浮点数时指定一个容差,不要将它们与 == 进行比较!

您可以为此定义一个almost_equal 函数,例如:

def almost_equal(x, y, tolerance):
    return abs(x-y) < tolerance

然后在上面的代码中,使用almost_equal(item[1], next[1], tolerance)而不是与==进行比较。

【讨论】:

    猜你喜欢
    • 2017-01-21
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    相关资源
    最近更新 更多