我想写一个非常简单的程序。我将获取一个数字列表,并检查列表中的所有成员是否被给定的整数平均除。以下是我的代码的现状:
def evenlist(lst,y):
print lst
for i in range(len(lst)):
print int(lst[i]) % y == 0
x = '2,5,6,8,10'
lst = x.split(',')
y = 2
if evenlist (lst,y): #(?????)
# Here is the problem....
print 'All are evenly divided by', y
else:
print 'All are not evenly divided by', y
如果evenlist(lst,y)都是真的,我怎么说呢。你知道吗
更新:
现在我的密码被破解了。更正代码:
def evenlist(lst,y):
print lst
result = []
for i in range(len(lst)):
result.append(int(lst[i]) % y == 0)
return result
x = '2,4,6,8,10'
lst = x.split(',')
y = 2
if all (evenlist(lst,y)):
print 'All are evenly divided by', y
else:
print 'All are not evenly divided by', y
当前,
evenlist
函数不返回任何内容。它只打印所有数字是否为偶数,然后隐式返回None
,在条件中被解释为False
。你知道吗要测试列表中的所有成员,请使用^{} 内置函数并返回其结果:
它的作用:它生成一个新的列表,其中每个元素都是条件(
True
或False
)的结果,然后测试该列表中的所有值是否都是True
(或其他“truthy”):示例:
继续您所在的路径,您可以将
evenlist()
转换为生成器,然后使用all()
对其进行迭代:嗨,你应该检查一下他们是否在def里
相关问题 更多 >
编程相关推荐