在python中,我如何编写这样的代码:“如果对列表的所有成员都为true,请执行此操作。”

2024-10-04 15:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个非常简单的程序。我将获取一个数字列表,并检查列表中的所有成员是否被给定的整数平均除。以下是我的代码的现状:

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

Tags: 代码in列表forbydefrangeresult
3条回答

当前,evenlist函数不返回任何内容。它只打印所有数字是否为偶数,然后隐式返回None,在条件中被解释为False。你知道吗

要测试列表中的所有成员,请使用^{}内置函数并返回其结果:

def evenlist(lst,y):
    return all(int(x) % y == 0 for x in lst)

它的作用:它生成一个新的列表,其中每个元素都是条件(TrueFalse)的结果,然后测试该列表中的所有值是否都是True(或其他“truthy”):

>>> lst = [2, 5, 6, 8, 10]
>>> [x % 2 == 0 for x in lst]
[True, False, True, True, True]
>>> all(x % 2 == 0 for x in lst)
False

示例:

>>> evenlist("2,5,6,8,10".split(','), 2)
False
>>> evenlist("2,12,6,8,10".split(','), 2)
True

继续您所在的路径,您可以将evenlist()转换为生成器,然后使用all()对其进行迭代:

def evenlist(lst,y):
   print lst
   for i in range(len(lst)):
       yield int(lst[i]) % y == 0

x = '2,5,6,8,10'
lst = x.split(',')
y = 2

if all(x for x in evenlist(lst,y)):
    print 'All are evenly divided by', y
else:
    print 'All are not evenly divided by', y

嗨,你应该检查一下他们是否在def里

def evenlist(lst,y):
 # print lst
x = 0
for i in range(len(lst)):
   x += int(lst[i]) % y
if x==0:
    return True
else:
    return False

x = '2,4,6,8,10'
lst = x.split(',')
y = 2
if evenlist (lst,y):
 print 'All are evenly divided by', y
else:
 print 'All are not evenly divided by', y

相关问题 更多 >

    热门问题