从列表中查找符合条件的编号



我需要编写一个脚本,根据两个条件从用户输入(列表(中选择一个数字:

  1. 是3的倍数
  2. 是所有数字中最小的

以下是我迄今为止所做的

if a % 3 == 0 and a < b:
print (a)
a = int(input())
r = list(map(int, input().split()))
result(a, r)

问题是,我需要创建一个循环,不断验证(x(个输入的这些条件。

看起来您希望ar中的值,而不是它自己的输入。下面是一个在r中迭代并检查哪些数字是3的倍数的例子,以及找到所有数字的最小值(不一定只有3的倍数(的例子:

r = list(map(int, input().split()))
for a in r:
if a % 3 == 0:
print(f"Multiple of 3: {a}")
print(f"Smallest of numbers: {min(r)}")
1 2 3 4 5 6 7 8 9 0
Multiple of 3: 3
Multiple of 3: 6
Multiple of 3: 9
Multiple of 3: 0
Smallest of numbers: 0

在一行中或通过生成器执行此操作可以通过优化内存分配来提高性能:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# The following is a generator
# Also: you need to decide if you want 0 to be included
all_threes = (x for x in my_list if x%3==0)
min_number = min(my_list)

最新更新