本文共 2319 字,大约阅读时间需要 7 分钟。
本文翻译自:
I have come across this: 我遇到了这个:
item = someSortOfSelection()if item in myList: doMySpecialFunction(item)
but sometimes it does not work with all my items, as if they weren't recognized in the list (when it's a list of string). 但有时它不能与我的所有项目一起使用,就像在列表中没有识别它们一样(当它是字符串列表时)。
Is this the most 'pythonic' way of finding an item in a list: if x in l:
? 这是在列表中查找项目的最“ pythonic”方式: if x in l:
吗?
参考:
如果您要查找一个元素,或者要在next
查找None
使用default,如果在列表中未找到该元素,则不会引发StopIteration
:
first_or_default = next((x for x in lst if ...), None)
Check there are no additional/unwanted whites space in the items of the list of strings. 检查字符串列表中的项目是否没有其他多余的空格。 That's a reason that can be interfering explaining the items cannot be found. 这就是可能无法解释项目的原因。
虽然Niklas B.的答案非常全面,但是当我们想在列表中查找某项时,有时获得其索引很有用:
next((i for i, x in enumerate(lst) if [condition on x]), [default value])
Finding the first occurrence 寻找第一次出现
There's a recipe for that in itertools
: 在itertools
有一个配方:
def first_true(iterable, default=False, pred=None): """Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true. """ # first_true([a,b,c], x) --> a or b or c or x # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x return next(filter(pred, iterable), default)
For example, the following code finds the first odd number in a list: 例如,以下代码查找列表中的第一个奇数:
>>> first_true([2,3,4,5], None, lambda x: x%2==1)3
You may want to use one of two possible searches while working with list of strings: 在处理字符串列表时,您可能想要使用两种可能的搜索之一:
if list element is equal to an item ('example' is in ['one','example','two']): 如果list元素等于一个项目([example]在['one','example','two']中):
if item in your_list: some_function_on_true()
'ex' in ['one','ex','two'] => True ['one','ex','two']中的'ex'=>真
'ex_1' in ['one','ex','two'] => False ['one','ex','two']中的'ex_1'=>否
if list element is like an item ('ex' is in ['one,'example','two'] or 'example_1' is in ['one','example','two']): 如果list元素像一个项目(“ ex”在['one,'example','two']或'example_1'在['one','example','two']中):
matches = [el for el in your_list if item in el]
or 要么
matches = [el for el in your_list if el in item]
then just check len(matches)
or read them if needed. 然后只需检查len(matches)
或根据需要阅读即可。
转载地址:http://oscnb.baihongyu.com/