[英]Get last element of type string in a list
假设我有一个不同类型的列表:
即
[7, 'string 1', 'string 2', [a, b c], 'string 3', 0, (1, 2, 3)]
是否有Pythonic方式返回'string 3'?
如果你有一个给定的类型,你可以使用几种理解来获得你需要的东西。
[el for el in lst if isinstance(el, given_type)][-1]
# Gives the last element if there is one, else IndexError
要么
next((el for el in reversed(lst) if isinstance(el, given_type)), None)
# Gives the last element if there is one, else None
如果这是你经常做的事情,你可以将它分解为一个函数:
def get_last_of_type(type_, iterable):
for el in reversed(iterable):
if isinstance(el, type_):
return el
return None
我认为最简单的方法是获取过滤列表的最后一个元素。
filter(lambda t: type(t) is type(''), your_list)[-1]
要么
[el for el in your_list if type(el) is type('')][-1]
强制性的itertools
解决方案:
>>> l = [7, 'string 1', 'string 2', 8, 'string 3', 0, (1, 2, 3)]
>>> from itertools import dropwhile
>>> next(dropwhile(lambda x: not isinstance(x, str), reversed(l)), None)
'string 3'
如果您因任何原因无法使用导入,则itertools.dropwhile
如下所示:
def dropwhile(predicate, iterable):
# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
iterable = iter(iterable)
for x in iterable:
if not predicate(x):
yield x
break
for x in iterable:
yield x
尝试这个
lst = [7, 'string 1', 'string 2', [a, b c], 'string 3', 0, (1, 2, 3)]
filtered_string = [ x for x in lst if type(x) is str]
现在你可以获得最后一个索引的任何索引
filtered_string[-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.