python,在列表中打印最长的字符串

标签 python

我的问题是编写一个返回最长字符串并忽略任何非字符串的函数,如果输入列表中没有字符串,那么它应该返回 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/

相关文章:

python - 在模型 django 中的每个字段上实现隐私的最佳方式

python - Tensorflow 第一层神经元的权重不会改变

python - 在列表中查找与另一个列表中的元素近似相等的元素的索引

python - python 中的梯度下降实现?

python - 如何在 PySpark 中对 DateTime 值进行编码?

Python 在字符串中使用通配符

python - 索引错误: list index out of range error when reversing a list

python - 批量创建需要事务原子性吗?

python - Numpy 索引 : Return the rest

Python:每秒运行循环并触发函数5秒