我需要生成0到500之间的100个随机值,并将偶数值存储在列表中,奇数存储在另一个值中。我被困在一开始。
import random
def randomval():
size=random.randint(0, 500)
return
if val%2==0:
listeven.append()
else:
listodd.append()
答案 0 :(得分:4)
both = [ random.randint(0, 500) for i in range(100) ]
odd = [ x for x in both if x % 2 == 1 ]
even = [ x for x in both if x % 2 == 0 ]
答案 1 :(得分:2)
在One Pass中完成所有操作 - 效率更高。
from random import randint
even, odd = [], []
for _ in range(100):
num = randint(0, 500)
if num % 2:
odd.append(num)
else:
even.append(num)
作为一项功能:
def get_random_even_and_odd(amount=100, _min=0, _max=500):
even, odd = [], []
for _ in range(amount):
num = randint(_min, _max)
if num % 2:
odd.append(num)
else:
even.append(num)
return even, odd
答案 2 :(得分:2)
解决方案取决于是否可以重复随机数。
random_values = [ random.randint(0, 500) for i in range(100) ]
odd = [ x for x in random_values if x % 2 ]
even = [ x for x in random_values if not x % 2 ]
如果您想获得唯一的随机数,我建议您使用shuffle
random_values = random.sample(range(0, 500), 100)
odd = [ x for x in random_values if x % 2 ]
even = [ x for x in random_values if not x % 2 ]
您可以使用生成器减少内存使用量,例如
random_values = (random.randint(0, 500) for i in xrange(100))
odd = []
even = []
for val in random_values:
if val % 2:
odd.append(val)
else:
even.append(val)