我的问题是编写一个返回最长字符串并忽略任何非字符串的函数,如果输入列表中没有字符串,那么它应该返回 None。
我的回答:
def longest_string(x):
for i in max(x, key=len):
if not type(i)==str:
continue
if
return max
longest_string(['cat', 'dog', 'horse'])
我是初学者,所以我不知道从哪里开始。如果这很简单,我们深表歉意。
最佳答案
我会这样做:
def longest_string(x):
Strings = [i for i in x if isinstance(i, str)]
return(max(Strings, key=len)) if Strings else None
关于python,在列表中打印最长的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70434028/