2

我花了几个小时解决这个问题,但程序不起作用(语法错误)。检查类似问题的答案没有帮助。下面的代码有什么问题?我想检查列表(密码)是否包含至少一个数字,以及其中包含一个大写字母和一个小写字母。请给我最简单的方法,我是初学者...

def checkio(password):    
    array = list(password)
    #for letter in array:
    if len(array) < 10 or len(array) > 64:
        return False
    if (any(l.isdigit() for l in array) and (any(l.isupper( for l in array) and (any(l.islower for l in array):
        return True
    else:
        return False
4

4 回答 4

2

你的括号是非常错误的。尝试这个。

def checkio(password):    
  array = list(password)
  #for letter in array:
  if len(array) < 10 or len(array) > 64:
      return False
  if ((any(l.isdigit() for l in array)) and (any(l.isupper() for l in array)) and ((any(l.islower() for l in array)))):
      return True
  else:
      return False
于 2014-11-10T23:04:11.107 回答
1

你可以这样做,你缺少一些括号,另一件事是,你说at least一个数字,长度应该是<1。您也不需要转换为列表,您可以迭代strings

def checkio(password):    
    if len(password) < 1 or len(password) > 64:
        return False
    if (any(x.isdigit() for x in password)) and (any(l.isupper for l in password)) and (any(l.islower for l in password)):
        return True
    else:
        return False

print checkio("StackO3f") #True

print checkio("S") #False

print checkio("sssss") #False
于 2014-11-10T23:04:55.987 回答
1

有时,如果您很好地格式化代码,这些事情是最容易看到的。你缺少一些括号:

def checkio(password):
    if 10 < len(password) or len(password) > 64:
        return False

    return (any(l.isdigit() for l in password) and
            any(l.isupper() for l in password) and
            any(l.islower() for l in password)):

请注意,您不必从密码构造一个列表——python 字符串是可迭代的并且具有明确定义的长度。

于 2014-11-10T23:00:01.140 回答
1

当你这样做时any(l.isdigit() for l in array),你正在创建一个生成器。必须“消耗”生成器才能使值正确。

在这种情况下,您最好使用列表来代替。也不需要调用array = list(password),因为字符串在 python 中是可迭代的。以下是代码的外观:

def checkio(password):    
    if len(password) < 10 or len(password) > 64:
        return False
    if any([c.isdigit() for c in password]) and any([c.islower() for c in password]) and any([c.isupper() for c in password]):
        return True
    else:
        return False

在这个版本中,any() 函数在使用[c.func() for c in password].

于 2014-11-10T23:15:25.390 回答