Python 列表帮助(查找最大数字)

发布于 2024-11-18 18:29:04 字数 160 浏览 1 评论 0原文

好吧,我写了这个脚本:

i=1024;
a=[0]*i;
for k in range(0,i):
    a[k]=(k*k*k*k-74*k*k+173) % 1000033
print a

我不明白如何找到列表中最大的数字及其位置。

Ok, I have this script that i wrote:

i=1024;
a=[0]*i;
for k in range(0,i):
    a[k]=(k*k*k*k-74*k*k+173) % 1000033
print a

I don't understand how to find the biggest number in the list AND its position.

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

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

发布评论

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

评论(5

‘画卷フ 2024-11-25 18:29:04

这是一种方法:

value = max(a)
index = a.index(value)

在您的示例中,值是 999926,索引是 2。

Here's one way:

value = max(a)
index = a.index(value)

In your example, value is 999926 and index is 2.

放低过去 2024-11-25 18:29:04
# create the list with a list comprehension
m = [(k*k*k*k-74*k*k+173) % 1000033 for k in range(i)]
# enumerate the values and pick the largest by value
pos, val = max(enumerate(m), key=lambda (pos, val): val)
# create the list with a list comprehension
m = [(k*k*k*k-74*k*k+173) % 1000033 for k in range(i)]
# enumerate the values and pick the largest by value
pos, val = max(enumerate(m), key=lambda (pos, val): val)
樱&纷飞 2024-11-25 18:29:04

只要保持运行轨迹,那么您就不需要列表:

largest = None
i = 1024

for k in range(i):
    a = (k ** 4 - 74 * k ** 2 + 173) % 1000033
    if not largest or largest[1] < a:
        largest = (k, a)

print(largest)

输出:

(2, 999926)

PS i = 1048576 花了几秒钟然后吐出:

(156865, 1000032L)

请注意,它在某处切换为长整数。这是 Python 2.6.1 的情况。

PPS 另请注意,此方法仅查找具有最大值的最低索引。要获得最高索引,请将 < 替换为 <=

(843168, 1000032L)

Just keep a running track, then you don't need the list:

largest = None
i = 1024

for k in range(i):
    a = (k ** 4 - 74 * k ** 2 + 173) % 1000033
    if not largest or largest[1] < a:
        largest = (k, a)

print(largest)

Output:

(2, 999926)

P.S. i = 1048576 took a couple seconds and spat out:

(156865, 1000032L)

Note that it switched to long integers in there somewhere. This is with Python 2.6.1.

P.P.S. Also note that this method only finds the lowest index with the maximum. To get the highest index, replace the < with <=:

(843168, 1000032L)
許願樹丅啲祈禱 2024-11-25 18:29:04
m = max(a)
m_index = a.index(m)
m = max(a)
m_index = a.index(m)
雪若未夕 2024-11-25 18:29:04
lst = [1,3,4,56,2,66,20,312]
print "%d found at index %d is the max of the list" % (max(lst), lst.index(max(lst)))
lst = [1,3,4,56,2,66,20,312]
print "%d found at index %d is the max of the list" % (max(lst), lst.index(max(lst)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文