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.
您只需构造一个生成器:
然后,您可以通过以下方式进行调用:
如果没有这样的元素,它将引发
StopIteration
错误。这个解决方案的好处是,您可以再次调用next(..)
,等等,以获得所有索引:你可以这样写:
您可以构造一个简单的函数来返回给定范围内元素的第一次出现。如果找不到匹配的元素,
None
将返回:你可以这样使用它:
但是,如果您不希望索引
0
不符合测试条件,请使用if first_match is None
而不是if not first_match
。你知道吗循环遍历每个元素并跟踪索引,如果第一个元素满足条件,则返回index,否则返回-1
结果:
相关问题 更多 >
编程相关推荐