python - 当列表为空时,如何获取列表的第一个元素或 `None`?

标签 python list

我可以这样做,但必须有更好的方法:

arr = []
if len(arr) > 0:
    first_or_None = arr[0]
else:
    first_or_None = None

如果我只执行 arr[0] 我会得到 IndexError。 我可以提供默认参数吗?

最佳答案

我认为你给出的例子绝对很好 - 它非常具有可读性并且不会遇到性能问题。

如果你真的希望它的代码更短,你可以使用三元运算符 python 等效项:

last_or_none = arr[0] if len(arr) > 0 else None

关于python - 当列表为空时,如何获取列表的第一个元素或 `None`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73176227/

相关文章:

algorithm - 这种类型的二进制搜索有名称吗?

python - 使用 Python 从字符串中提取值

list - flutter : Unsupported operation: Cannot add to an unmodifiable list

python - 在双 for 循环 python 中打印字符串的每一行时出现问题

python - 将列添加到 DataFrame 时忽略列长度

python - 将计数器列表保存到 python 中的文件中

python - 打印出文本文件中的句子数

Python:如何添加两个列表,其中与该键的值相同的键没有重复值?

c++ - OpenCV/C++ 程序比它的 numpy 对应程序慢,我该怎么办?

python - Pytest 断言超时?