简体   繁体   English

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

[英]the simple way to check if the elements of a list or set are single type?

i need to write a piece of code if all the elements are int or all are string then return true,else return false 我需要编写一段代码,如果所有元素都是int或者都是字符串然后返回true,否则返回false

[1,'1','a','b'] False
[1,2,3,4] True
['apple','orange','melon'] True
['1', 2, 3, 4] False

my solution is these 我的解决方案是这些

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

i think it should be better. 我认为应该会更好。

This code checks generally if all elements are of the same type: 此代码通常检查所有元素是否属于同一类型:

len(set(type(elem) for elem in elems)) == 1

It answers the title of your question, but works differently than your solution (which returns false for a list of floats). 它回答了您的问题的标题,但其工作方式与您的解决方案不同(对于浮点数列表,它返回false)。

If you require all your elements in list l to be of a certain type, eg int , then the following is a very efficient method: 如果要求列表l所有元素都是某种类型,例如int ,那么以下是一种非常有效的方法:

any(not isinstance(e, int) for e in l)

It short-circuits, ie on the first occurrence of a list element that is not if type int it evaluates to False . 它是短路的,即在第一次出现的list元素中,如果类型为int则它不会计算为False

If you require all your elements in list l to just be of the same type and do not provide this type as input information there is at least one element in the list, then this a is the analogon: 如果您要求列表l所有元素只是相同类型并且不提供此类型作为输入信息,则列表中至少有一个元素,那么这是一个类比:

all(type(e) == type(l[0])) for e in l)
type(l[0]) in [int, str] and all( type(e) == type(l[0]) for e in l)
def all_of(iterable, types=[str,int])
    actual_types = set(map(type, iterable))
    return len(actual_types) == 1 and next(iter(actual_types)) in types
In [32]: len(set(map(type, [1, 2, 3]))) == 1
Out[32]: True

In [33]: len(set(map(type, [1, 2, '3']))) == 1
Out[33]: False

If you want to check that the sequence is all of a specific type... 如果要检查序列是否都是特定类型...

def check_all_same_type(sequence, typ, strict=True):
    if strict:
        return all(type(item) == typ for item in sequence)
    return all(isinstance(item, typ) for item in sequence)

If you just wanted to make sure they're all the same type... 如果你只是想确保它们都是相同的类型......

types = set(type(item) for item in sequence)
all_same = (len(types) == 1)
if all_same:
    print "They're all a type of", type(next(iter(types)))

i think it will be faster: 我认为它会更快:

for ints : ints

>>> ints = set(list(range(10)))
>>> ints
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>
>>>
>>>
>>> l = set([1,2,3,'d'])
>>> l - ints
set(['d'])
>>>
>>> l = set([1,2,'3','d'])
>>> l - ints
set(['3', 'd'])
>>>

it possible to use this method for str's . 可以将此方法用于str's

Here's how I might do it. 这是我如何做到的。 After the initial conditions are checked the function will stop checking as soon as an elem's type fails to pass. 检查初始条件后,只要elem的类型无法通过,函数就会停止检查。 It also handles empty lists. 它还处理空列表。

def check_elem_types(l):
    return bool(l) and type(l[0]) in (int, str) and all(type(e) == type(l[0]) for e in l[1:])

If you wanted to handle unicode strings (in Python 2.x), you would instead need this: 如果你想处理unicode字符串(在Python 2.x中),你需要这样做:

def check_elem_types(l):
    return (bool(l) and isinstance(l[0], (int, basestring)) and
            all(type(e) == type(l[0]) for e in l[1:]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM