在一维列表中循环遍历二维列表



我有两个列表:

  • 一维:x_int_loc = [0,1,2,3,4,5]
  • 二维:xtremes = [[0,2],[0,3],[1,3],[1,5],[2,5],[3,6],[4,8]]

我试图收集x_int_loc中每个元素在xtremes列表中的值范围内的次数。也就是说,1(在列表x_int_loc中)的计数将是2,因为它出现在[0,2], [0,3]等中。

虽然这看起来很简单,但我在循环这些列表时遇到了一些困难。下面是我的代码:

for i in range(len(x_int_loc)):
    while k < len(xtremes):
        if x_int_loc[i]>xtremes[k][0] and xtremes[k][1] > x_int_loc[i]:
            count[i] = count[i]+1
print(count[:])

你们谁能告诉我我哪里错了?

您永远不会增加k,或者在i增加时重置它。最小的修改是:

for i in range(len(x_int_loc)):
    k = 0
    while k < len(xtremes):
        if x_int_loc[i]>xtremes[k][0] and xtremes[k][1] > x_int_loc[i]:
            count[i] = count[i]+1
        k += 1

使用while循环和手动索引是不好的做法;这清楚地表明,它很容易出错。为什么不直接在xtremes上循环for呢?你真正需要的是:

count = [sum(x < n < y for x, y in xtremes) for n in x_int_loc]

得到:

>>> count
[0, 2, 3, 2, 3, 2]

除非您对优化过于挑剔,否则在一般情况下,以下解决方案将是最优的

>>> x_int_loc = [0,1,2,3,4,5]
>>> xtremes = [[0,2],[0,3],[1,3],[1,5],[2,5],[3,6],[4,8]]
>>> xtremes_ranges = [xrange(r[0]+1,r[1]) for r in xtremes]
>>> [(x, sum(x in r for r in xtremes_ranges)) for x in x_int_loc]
[(0, 0), (1, 2), (2, 3), (3, 2), (4, 3), (5, 2)]

最新更新