【问题标题】:Indexing a list for value within certain range为特定范围内的值索引列表
【发布时间】:2021-09-14 14:35:56
【问题描述】:

我有一个列表 x = [2, 3, 3, 4, 5]y = [10, 40, 50, 9, 7]。如果x <= 3y => 30,我想打印xy 中元素的索引列表。所以在这种情况下,它将是 (3, 40)(3, 50) 对。因此,我想要一个他们的索引列表作为我的输出。所以result = [1, 2]

我试着写了一个for循环如下:

result = []
for i in x, y:
    if x <= 3 and y => 30:
        result.append(enumerate(i))
print(result)

【问题讨论】:

  • =&gt; 不是 Python 中的运算符。你的意思是&gt;=

标签: python list loops


【解决方案1】:

仅提及另一种使用np.where 实现此目的的方法:

import numpy as np

# need to convert x and y into array first
x = np.array([2, 3, 3, 4, 5])
y = np.array([10, 40, 50, 9, 7])

result = np.where((x >= 3) & (y >= 30))[0].tolist()

print(result)

【讨论】:

    【解决方案2】:

    假设xy 的长度相同(否则您必须检查哪个更短):

    result=[]
    for i in range(len(x)):
        if x[i] <= 3 and y[i] >= 30:
            result.append(i)
    
    print(result)
    

    【讨论】:

      【解决方案3】:

      我想这可能是你的目标:

      >>> result = []
      >>> xlist=[2,3,3,4,5]
      >>> ylist=[10,40,50,9,7]
      >>> for i, (x,y) in  enumerate(zip(xlist,ylist)):
              if x <= 3 and y >= 30:
                  result.append(i)
      >>> result
      [1, 2]
      

      【讨论】:

        【解决方案4】:

        您可以使用列表推导:

        result=[i for i in range(len(x)) if x[i] >=3 and y[i]>=30]
        
        print(result)
        
        #[1, 2]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-14
          • 1970-01-01
          • 2022-10-14
          • 2020-08-18
          • 1970-01-01
          • 2012-07-08
          • 1970-01-01
          • 2012-11-21
          相关资源
          最近更新 更多