[英]Get last element of type string in a list
Suppose I have a list of different types: 假设我有一个不同类型的列表:
ie 即
[7, 'string 1', 'string 2', [a, b c], 'string 3', 0, (1, 2, 3)]
Is there a Pythonic way to return 'string 3' ? 是否有Pythonic方式返回'string 3'?
If you have a given type, you can use several kinds of comprehensions to get what you need. 如果你有一个给定的类型,你可以使用几种理解来获得你需要的东西。
[el for el in lst if isinstance(el, given_type)][-1]
# Gives the last element if there is one, else IndexError
or 要么
next((el for el in reversed(lst) if isinstance(el, given_type)), None)
# Gives the last element if there is one, else None
If this is something you're doing often enough, you can factor it into a function: 如果这是你经常做的事情,你可以将它分解为一个函数:
def get_last_of_type(type_, iterable):
for el in reversed(iterable):
if isinstance(el, type_):
return el
return None
I'd think the easiest way would be to grab the last element of a filtered list. 我认为最简单的方法是获取过滤列表的最后一个元素。
filter(lambda t: type(t) is type(''), your_list)[-1]
or 要么
[el for el in your_list if type(el) is type('')][-1]
Obligatory itertools
solution: 强制性的
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'
In case you can't use imports for whatever reason, the polyfill for itertools.dropwhile
is as follows: 如果您因任何原因无法使用导入,则
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
try this 尝试这个
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]
now you can get any index of it for last index 现在你可以获得最后一个索引的任何索引
filtered_string[-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.