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

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

``````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
``````

8 个回复

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

``````any(not isinstance(e, int) for e in 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
``````

``````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)
``````

``````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)))
``````

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

``````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:])
``````

``````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:]))
``````
2 创建单一类型对象的列表

3 单一类型的小数或枚举

2014-11-17 17:09:01 1 61   xsd
4 从单一类型创建不同的POCO

2011-01-05 06:00:30 1 119   .net/ poco
5 Scala：检查2个变量是否属于同一类型

2015-05-10 14:53:48 2 1002   types
6 Strapi 中是否有针对单一类型的草稿系统？

2020-04-28 09:23:11 1 344   strapi
8 单一类型的性状中的双向链接

2011-05-10 02:12:19 1 171   scala
9 如何将单一类型的不同功能公开给不同的模块？

10 单一类型的Clang回归或向量化

2016-10-27 01:11:08 0 38   c++/ llvm