将此英文标题翻译成中文并不包含任何特殊字符或引号:'循环遍历1-D列表中的2-D列表'

2024-04-20 04:14:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个清单:

  • 一维: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[:])

你们谁能告诉我哪里出了问题吗?你知道吗


Tags: in元素密码列表forlenifcount
2条回答

你从不增加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循环是不好的做法;这清楚地表明,它容易出错。为什么不直接在for上循环xtremes?您真正需要的是:

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)]

相关问题 更多 >