相关疑难解决方法(0)

检查列表或集合的元素是否是单一类型的简单方法?

我需要编写一段代码,如果所有元素都是int或者都是字符串然后返回true,否则返回false

[1,'1','a','b'] False
[1,2,3,4] True
['apple','orange','melon'] True
['1', 2, 3, 4] False
Run Code Online (Sandbox Code Playgroud)

我的解决方案是这些

def foo(l):
    t = type(l[0])
    if t is not str and t is not int:
        return False
    for x in l:
        if t != type(x):
            return False
    return True
Run Code Online (Sandbox Code Playgroud)

我认为应该会更好.

python

4
推荐指数
1
解决办法
123
查看次数

标签 统计

python ×1