[英]I want to change random numbers from the list of them to the minimal meaning of list
I create a list of 'a' random numbers. 我创建一个“ a”随机数列表。 And than I need to change odd numbers to the minimum number of this list.
而且我需要将奇数更改为该列表的最小数量。 but it doesn't change any number, what's wrong?
但它没有改变任何数字,怎么了?
import random
a = int(input('Num -> '))
s = []
for i in range(a):
s.append(random.randint(0,10))
if s[i]%2!=0:
s[i]=min(s)
You program does, indeed, change the numbers as you requested. 实际上,您的程序确实会根据您的要求更改编号。 I added trivial
print
statements to track this: 我添加了一些琐碎的
print
语句来跟踪:
import random 随机导入
a = 10
s = []
for i in range(a):
s.append(random.randint(0,10))
if s[i]%2==0:
print("Changing", i)
print("\tbefore", s)
s[i]=min(s)
print("\t after", s)
Output: 输出:
Changing 1
before [3, 10]
after [3, 3]
Changing 6
before [3, 3, 5, 9, 9, 1, 8]
after [3, 3, 5, 9, 9, 1, 1]
Changing 7
before [3, 3, 5, 9, 9, 1, 1, 6]
after [3, 3, 5, 9, 9, 1, 1, 1]
Changing 8
before [3, 3, 5, 9, 9, 1, 1, 1, 6]
after [3, 3, 5, 9, 9, 1, 1, 1, 1]
Changing 9
before [3, 3, 5, 9, 9, 1, 1, 1, 1, 0]
after [3, 3, 5, 9, 9, 1, 1, 1, 1, 0]
As you can see, the even numbers do get replaced with the list minimum. 如您所见,偶数确实被列表中的最小值所取代。 Your claim that it doesn't change any number is incorrect.
您声称它不会更改任何数字是不正确的。
If you want to change odd numbers, then you need to invert your check: 如果要更改奇数 ,则需要反转支票:
if s[i]%2 == 1:
changed if s[i]%2==0
to if s[i]%2!=0
to pick out the odd numbers. if s[i]%2==0
更改为if s[i]%2!=0
,则选择奇数。 The first way will change even numbers 第一种方法将改变偶数
import random
a = int(input('Num -> '))
# creates your list of x random numbers
s = []
for i in range(a):
s.append(random.randint(0,10))
# change odd numbers to the min of the original list
for i in range(a):
if s[i]%2!=0:
s[i]=min(s)
so let's say a is 10: 因此,假设a为10:
>>> [2, 2, 8, 1, 2, 2, 10, 7, 5, 7]
now change all odd numbers to min (in this case it's '1') 现在将所有奇数更改为最小值(在本例中为“ 1”)
>>> [2, 2, 8, 1, 2, 2, 10, 1, 1, 1]
The answer below works too, it's just a matter of if you need it to change after each iteration of creating the list, or create the list first, and then apply your rule. 以下答案也适用,这只是您是否需要在创建列表的每次迭代后进行更改,还是先创建列表,然后应用您的规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.