我这里有一定数量...
x = 6
还有两个清单...
list1 = [1, 5, 10]
list2 = [3, 7, 20]
我想找到特定数字6的位置,分别位于list1和list2的5到7之间。
像6一样位于list1和list2的“第一索引”之间(基于0),这意味着两个列表都必须进行迭代并比较数字
for a,b in zip(list1,list2):
if a <= x <=b:
以上for循环的细节是这样的
[(1,3),(5,7),(10,20)]
并且x
属于元组的第一个索引[(0),(1),(2)]
我怎么能得到这个?
使用next
和enumerate
:
>>> x = 6
>>> next((i for i, (a, b) in enumerate(zip(list1, list2)) if a<=x<=b), None)
1
enumerate
从传递给它的iterable / iterator中返回index和item,next
否则从iterator中返回第一个item None
。
>>> list(enumerate(zip(list1, list2)))
[(0, (1, 3)), (1, (5, 7)), (2, (10, 20))]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句