检查数组中是否存在元素

问题描述 投票:0回答:7

在 PHP 中,有一个名为

isset()
的函数来检查某些内容(如数组索引)是否存在并具有值。 Python 怎么样?

我需要在数组上使用它,因为有时我会收到“IndexError:列表索引超出范围”。

我想我可以使用try/catch,但这是最后的手段。

python
7个回答
119
投票

三思而行(LBYL):

if idx < len(array):
    array[idx]
else:
    # handle this

请求原谅比请求许可更容易(EAFP):

try:
    array[idx]
except IndexError:
    # handle this

在Python中,EAFP似乎是流行且首选的风格。它通常更可靠,并且避免了一整类错误(检查时间与使用时间)。在所有其他条件相同的情况下,建议使用

try
/
except
版本 - 不要将其视为“最后的手段”。

此摘录来自上面链接的官方文档,支持使用 try/ except 进行流量控制:

这种常见的 Python 编码风格假设存在有效的键或属性,并在假设证明错误时捕获异常。 这种干净快速的风格的特点是存在许多 try 和 except 语句。


51
投票

EAFP 与 LBYL

我理解你的困境,但 Python 不是 PHP,并且被称为“更容易请求宽恕而不是请求许可”的编码风格(或简称 EAFP)是 Python 中常见的编码风格 查看来源(来自

文档

):

EAFP

- 请求原谅比请求许可更容易。这种常见的 Python 编码风格假设存在有效的键或属性,并在假设证明错误时捕获异常。这种干净快速的风格的特点是存在许多 try 和 except 语句。该技术与许多其他语言(例如 C)常见的 LBYL 风格形成对比。

所以,基本上,
在这里使用 try-catch 语句并不是最后的手段;这是一种常见的做法

Python 中的“数组”

PHP 有关联数组和非关联数组,Python 有列表、元组和字典。列表类似于非关联 PHP 数组,字典类似于关联 PHP 数组。

如果你想检查“array”中是否存在“key”,你必须首先知道它在Python中是什么类型,因为当“key”不存在时,它们会抛出不同的错误:

>>> l = [1,2,3] >>> l[4] Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> l[4] IndexError: list index out of range >>> d = {0: '1', 1: '2', 2: '3'} >>> d[4] Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> d[4] KeyError: 4

如果您使用 EAFP 编码风格,您应该适当地捕获这些错误。

LBYL 编码风格 - 检查索引是否存在

如果您坚持使用 LBYL 方法,这些是适合您的解决方案:

  • 对于列表

    只需检查长度,如果possible_index < len(your_list),则

    your_list[possible_index]
    存在,否则不存在:
    
    
    >>> your_list = [0, 1, 2, 3] >>> 1 < len(your_list) # index exist True >>> 4 < len(your_list) # index does not exist False

  • 对于字典

    ,您可以使用 in 关键字,如果

    possible_index in your_dict
    ,则
    your_dict[possible_index]
    存在,否则不存在:
    
    
    >>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3} >>> 1 in your_dict # index exists True >>> 4 in your_dict # index does not exist False

    
    
    
  • 有帮助吗?


15
投票
编辑

:经过澄清,新答案: 请注意,PHP 数组与 Python 的数组有很大不同,它将数组和字典组合成一个混乱的结构。 Python 数组始终具有从

0

len(arr) - 1
的索引,因此您可以检查索引是否在该范围内。不过,
try/catch
是一种以Python方式完成此操作的好方法。

如果您询问 PHP“数组”(Python 的

dict

)的哈希功能,那么我之前的答案仍然有效:


`baz` in {'foo': 17, 'bar': 19} # evaluates as False `foo` in {'foo': 17, 'bar': 19} # evaluates as True



9
投票
has_key

快速高效。


使用哈希代替数组:

valueTo1={"a","b","c"} if valueTo1.has_key("a"): print "Found key in dictionary"



2
投票
dir()

来产生与 PHP 的

isset()
类似的行为,例如:

if 'foo' in dir(): # returns False, foo is not defined yet. pass foo = 'b' if 'foo' in dir(): # returns True, foo is now defined and in scope. pass

dir()

返回当前范围内的名称列表,更多信息可以在此处找到:

http://docs.python.org/library/functions.html#dir
.


0
投票

try- except 在这里不是正确的范例。

如果您不小心得到负指数,您会大吃一惊。

更好的解决方案是自己提供测试功能:

def index_in_array(M, index): return index[0] >= 0 and index[1] >= 0 and index[0]< M.shape[0] and index[1] < M.shape[1]



0
投票
isset()

: #!/usr/bin/env python3 # "defaultdict" for the quick test from collections import defaultdict def isset(mydict, *mykeys): for thiskey in mykeys: if thiskey in mydict: if thiskey == mykeys[-1]: return True else: mydict = mydict[thiskey] else: return False testdict = defaultdict(dict) testdict['a']['b'] = 'UU' res = isset(testdict,'a') print(res) # True res = isset(testdict,'a','b') print(res) # True res = isset(testdict,'b') print(res) # False res = isset(testdict,'a','b','c') print(res) # False res = isset(testdict,'a','bb') print(res) # False

	
© www.soinside.com 2019 - 2024. All rights reserved.