
[英]pythonic way to check if any elements of a list is present in a set
[英]the simple way to check if the elements of a list or set are single type?
我需要编写一段代码,如果所有元素都是int或者都是字符串然后返回true,否则返回false
[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
我认为应该会更好。
此代码通常检查所有元素是否属于同一类型:
len(set(type(elem) for elem in elems)) == 1
它回答了您的问题的标题,但其工作方式与您的解决方案不同(对于浮点数列表,它返回false)。
如果要求列表l
所有元素都是某种类型,例如int
,那么以下是一种非常有效的方法:
any(not isinstance(e, int) for e in l)
它是短路的,即在第一次出现的list元素中,如果类型为int
则它不会计算为False
。
如果您要求列表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'])
>>>
可以将此方法用于str's
。
这是我如何做到的。 检查初始条件后,只要elem的类型无法通过,函数就会停止检查。 它还处理空列表。
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:])
如果你想处理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.