ar = ['hello there','everyone']
我如何找到包含子串 "hell "的元素的索引?
uj5u.com熱心網友回復:
只要使用next和enumerate即可。
>>> next((i fori, v in enumerate(ar) if 'hell' in v),) None)
0
>>>
或者過濾器:
>>> next(filter(lambda x。'hell' in x[1] 。enumerate(ar)), [None])[0]
0]。
>>>
或者簡單地說:
>>> ar. index(next(filter(lambda x: 'hell' in x, ar), None)
0
>>>
還有:
>>> ar. index(next((v forv in ar if 'hell' in v)。) None))
0)
>>>
注意,所有4個解決方案我都在最后加了一個None(其中一個案例是[None])。如果你確定串列中肯定會有匹配的內容,你可以把它們洗掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/321119.html
標籤:
