我必须使用Python编写一个程序,它应该要求用户输入整数来组成一个数字列表。然后我必须检查此列表中至少有一个数字是否为3位数。我怎样才能做到这一点?我应该使用'for'声明。我是这样开始的:
numbers_list = []
while True:
try:
n = int(input("Enter an integer (press ENTER to end the program): "))
except ValueError:
break
else: numbers_list.append(n)
然后我尝试这样做,但它没有用:
num = False
for num in numbers:
if len(num) == 3:
num = True
break
print(num)
答案应该是:例如input = [1,101,2000],然后输出为True;如果input = [1,2,3],则输出为False
答案 0 :(得分:0)
如果给定列表中的任何一个元素满足特定条件,则使用any
函数返回bool值。
numbers_list = []
while True:
try:
n = int(input("Enter an integer (press ENTER to end the program): "))
except ValueError:
break
else: numbers_list.append(n)
print(any(len(str(i))>2 for i in numbers_list))
如果列表中的任何一个元素的长度大于2,则返回true
。
如果元素具有完全三位数,则返回true,然后将上述any
语句更改为,
print(any(len(str(i))==3 for i in numbers_list))