📜  python list 安全弹出 - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:32.805000             🧑  作者: Mango

代码示例1
In [1]: from typing import List, Any

In [2]: x = [{"count": 100}, {"count": 30}]
# use this function
In [3]: def defaultable_pop(input_list: List, index: int, default_value: Any = None) -> Any:
   ...:     try:
   ...:         return input_list.pop(index)
   ...:     except IndexError:
   ...:         return default_value
   ...:
#                                list, index, (default of empty dict)
In [4]: y: int = defaultable_pop(x, 0, dict({})).get("count", 0)

In [5]: y
Out[5]: 100

# As opposed to:
# y: int = x[0].get("count", 0) if len(x) > 0 else 0