An easy way to check if list or set items are single?

I need to write a piece of code, if all the int elements or all are strings, then return true, else return false

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

My solution is

 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.

+4
source share
8 answers
 type(l[0]) in [int, str] and all( type(e) == type(l[0]) for e in l) 
+2
source

This code usually checks 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 it works differently than your solution (which returns false for the list of floats).

+11
source

If you need all of your items in list l particular type, for example. int , then this is a very efficient method:

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

This is a short circuit, that is, at the first occurrence of a list item, which is not if type int evaluates to False .

If you need all your elements in the list l only one type and do not provide this type as input, there is at least one element in the list, then this is an analogue:

 all(type(e) == type(l[0])) for e in l) 
+3
source
 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 
+1
source
 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 
+1
source

If you want to check that a sequence is of a particular 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 want to make sure they are all the same ...

 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))) 
+1
source

I think it will be faster:

for 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']) >>> 

You can use this method for str's .

0
source

Here is how I can do this. After checking the initial conditions, the function ceases to be checked as soon as the type elem fails. It also processes 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 want to process Unicode strings (in Python 2.x), you will need the following:

 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:])) 
0
source

Source: https://habr.com/ru/post/1433962/


All Articles