在列表中搜索一系列数字,但返回第一个examp的索引

2024-04-25 01:16:45 发布

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

I have a list that I want to search for values from 500-535 in and I want to return the index for the first value found that is within that range.

mylist =[321, 344, 999, 512, 675, 555, 500]

rainday=forecastlist.index(range(500,531))

if not rainday:
    print("Empty")

Obviously this isn't working. I want it to return 3. I don't want the location of the other values at this time, just the first one.


Tags: thetoforsearchindexreturnthathave
3条回答

您只需构造一个生成器:

generator = (i for i,x in enumerate(mylist) if x in range(500,531))

然后,您可以通过以下方式进行调用:

first_index = next(generator)

如果没有这样的元素,它将引发StopIteration错误。这个解决方案的好处是,您可以再次调用next(..),等等,以获得所有索引:

>>> generator = (i for i,x in enumerate(mylist) if x in range(500,531))
>>> next(generator)
3
>>> next(generator)
6
>>> next(generator)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

你可以这样写:

generator = (i for i,x in enumerate(mylist) if x in range(500,531))
first_index = next(generator)
try:
    rainday=next(generator)
except StopIteration:
    print("Empty")

您可以构造一个简单的函数来返回给定范围内元素的第一次出现。如果找不到匹配的元素,None将返回:

def first_occurrence(lst, range_):
    for pos, n in enumerate(lst):
        if n in range_:
            return pos

你可以这样使用它:

first_match = first_occurrence(forecastlist, range(500,531))
if not first_match:
    print('empty')

但是,如果您不希望索引0不符合测试条件,请使用if first_match is None而不是if not first_match。你知道吗

循环遍历每个元素并跟踪索引,如果第一个元素满足条件,则返回index,否则返回-1

mylist =[321, 344, 999, 512, 675, 555, 500]

def check_ele_in_range(my_list, low, high):
    for ind, ele in enumerate(my_list):
        if low < ele < high:
            return ind
    return -1

print(check_ele_in_range(mylist, 500, 535))
print(check_ele_in_range([1,2,3], 500, 535))

结果:

3
-1

相关问题 更多 >