在python列表中找到特定数字的最小倍数

发布于 2025-01-23 20:48:38 字数 250 浏览 0 评论 0原文

想象一下,您有一个数字列表,您想找到符合特定条件的数字索引(例如3)。然后,我们希望拥有最小的索引(满足上述条件)是一定数量的倍数(这里4)。以下可能是一个好的开始。您将为其余的代码提供什么建议?

a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16]
b = 4

输出= [i,i,x in Enumerate(a)如果x> 3]

打印(输出) '''

Imagine that you have a list of numbers and you would like to find the index of numbers meeting a certain condition (say > 3). We would then like to have the smallest index (meeting the above condition) being a multiple of a certain number (here 4). Below might be a good start. What would you suggest for the rest of the code?

a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16]
b = 4

output = [i for i, x in enumerate(a) if x > 3]

print(output)
'''

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

三岁铭 2025-01-30 20:48:38

如果要查找Minumim索引,则可以使用min()函数:

a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16] 
b = 4

output = [i for i, x in enumerate(a) if x > 3]

print(output, min(output))

If you want to find the minumim index, you can use the min() function:

a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16] 
b = 4

output = [i for i, x in enumerate(a) if x > 3]

print(output, min(output))
撩发小公举 2025-01-30 20:48:38

这些索引已经通过上面给出的代码获得。您需要做的就是找到b可除外的最小索引。您可以如下实现:

a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16]
b = 4
# outputGT3 = output of all numbers > 3
outputGT3 = [i for i, x in enumerate(a) if x > 3]
print(outputGT3)
# outputDBb = output of all numbers divisible by b
outputDBb = [x for i, x in enumerate(outputGT3) if x % b==0]
print(outputDBb[0])
# since outputDBb is already sorted, the 1st element is the smallest.

The indices are already obtained by the code given above. All you need to do is find the smallest index divisible by b. You can achieve it as follows:

a = [1, 2, 3, 1, 2, 3, 5, 8, 9, 10 ,12, 12, 15, 16]
b = 4
# outputGT3 = output of all numbers > 3
outputGT3 = [i for i, x in enumerate(a) if x > 3]
print(outputGT3)
# outputDBb = output of all numbers divisible by b
outputDBb = [x for i, x in enumerate(outputGT3) if x % b==0]
print(outputDBb[0])
# since outputDBb is already sorted, the 1st element is the smallest.
等往事风中吹 2025-01-30 20:48:38

这个问题与列表无关:

a, b = 3, 4
n = a + b/2
result = n - (n%b)

This question is unrelated to lists:

a, b = 3, 4
n = a + b/2
result = n - (n%b)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文