lap*_*ete 3 python arrays loops list
假设我有一个不同类型的列表:
即
[7, 'string 1', 'string 2', [a, b c], 'string 3', 0, (1, 2, 3)]
Run Code Online (Sandbox Code Playgroud)
是否有Pythonic方式返回'string 3'?
Ada*_*ith 12
如果你有一个给定的类型,你可以使用几种理解来获得你需要的东西.
[el for el in lst if isinstance(el, given_type)][-1]
# Gives the last element if there is one, else IndexError
Run Code Online (Sandbox Code Playgroud)
要么
next((el for el in reversed(lst) if isinstance(el, given_type)), None)
# Gives the last element if there is one, else None
Run Code Online (Sandbox Code Playgroud)
如果这是你经常做的事情,你可以将它分解为一个函数:
def get_last_of_type(type_, iterable):
for el in reversed(iterable):
if isinstance(el, type_):
return el
return None
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
652 次 |
| 最近记录: |