简体   繁体   English

有没有办法从随机数中找到最大的数?

[英]is there a way to find the greatest number from random numbers?

i am writing a code to find the max and min number from a python list.我正在编写代码以从 python 列表中查找最大和最小数。 if i provide numbers in list it is easy to get output, but i want to get output from random numbers, how to do it.如果我在列表中提供数字,则很容易获得输出,但我想从随机数中获得输出,该怎么做。

i have tried using max() but it does not work with random numbers我试过使用 max() 但它不适用于随机数

import random
list = []
print (len(list))
for i in range(1,10):
    print (random.randint(100,200))
for num in list:
     list = [random]
     print (list)

also i have tried using我也试过使用

index = list.index(max(list))
print ('index of max is ', index)

this works if i provide the numbers, but not with random.如果我提供数字,这有效,但不是随机的。

the output of both max and min is same. max 和 min 的输出相同。

You are not filling your list with numbers, you are just printing them.你不是用数字填满你的清单,你只是在打印它们。 Your list is actually empty.您的列表实际上是空的。

Try this:尝试这个:

import random

list_ = [random.randint(100,200) for _ in range(10)]
print(list_)
print(max(list_))

PS Don't name variables equal to the keywords, like list , dict etc. It is very bad idea that can lead to various errors. PS 不要命名变量等于关键字,如listdict等。这是一个非常糟糕的主意,可能会导致各种错误。

First you need to populate the list, and later find the minimum and maximum values:首先你需要填充列表,然后找到最小值和最大值:

import random

lst = []
for i in range(1, 10):
    lst.append(random.randint(100, 200))

print(max(lst))
print(min(lst))

Notice that it's more idiomatic to use a list comprehension, as shown in @vurmux's answer.请注意,使用列表推导式更为惯用,如@vurmux 的回答所示。

print (len(list)) //It will always print 0. Because list is empty at this time. print (len(list)) //会一直打印0,因为此时list为空。 You need to populate it with random numbers.您需要用随机数填充它。

Also it is not a good practice to use Python Keywords as name of lists,sets,variables etc. It could raise errors.此外,使用 Python 关键字作为列表、集合、变量等的名称也不是一个好习惯。它可能会引发错误。 You have used list which a constructor for creating lists.您已经使用了 list ,它是一个用于创建列表的构造函数。

Here's what you need to do:-这是您需要做的:-

import random
numlist = []

for i in range(1,10):
     numlist.append(random.randint(100,200))

print(max(numlist))
print(min(numlist))

Read about max here :- https://docs.python.org/3/library/functions.html#max在此处阅读有关 max 的信息:- https://docs.python.org/3/library/functions.html#max

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM