我需要编写一段代码,如果所有元素都是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 ×1