建立随机乘法示例列表 [英] Building a list of random multiplication examples
问题描述
我有两个100个元素的列表,其中填充了1到10之间的随机数.
I have two 100-element lists filled with random numbers between 1 and 10.
我想列出一个随机选择的数字的乘法,该乘法一直进行到生成大于50的乘积为止.
I want to make a list of multiplications of randomly selected numbers that proceeds until a product greater than 50 is generated.
我如何获得这样一个列表,其中每个元素都是一个产品及其两个因素?
How can I obtain such a list where each element is a product and its two factors?
这是我尝试的代码.我认为它有很多问题.
Here is the code I tried. I think it has a lot of problems.
import random
list1 = []
for i in range(0,1000):
x = random.randint(1,10)
list1.append(x)
list2 = []
for i in range(0,1000):
y = random.randint(1,10)
list2.append(y)
m=random.sample(list1,1)
n=random.sample(list2,1)
list3=[]
while list3[-1][-1]<50:
c=[m*n]
list3.append(m)
list3.append(n)
list3.append(c)
print(list3)
我想要的输出
[[5.12154,4.94359,25.3188],[1.96322,3.46708,6.80663],[9.40574, 2.28941,21.5336],[4.61705,9.40964,43.4448],[9.84915,3.0071,29.6174],[8.44413,9.50134,80.2305]]
[[5.12154, 4.94359, 25.3188], [1.96322, 3.46708, 6.80663], [9.40574, 2.28941, 21.5336], [4.61705, 9.40964, 43.4448], [9.84915, 3.0071, 29.6174], [8.44413, 9.50134, 80.2305]]
更具描述性:
[[[randomfactor,randomfactor,product],......,[[randomfactor, randomfactor,大于50]]
[[randomfactor, randomfactor, product],......,[[randomfactor, randomfactor, greater than 50]]
推荐答案
准备两个包含1000个数字的列表,每个列表中的数字从1到10浪费了内存.如果这只是一种简化,而您想从否则得到的列表中提取,只需替换
Prepping two lists with 1000 numbers each with numbers from 1 to 10 in them is wasted memory. If that is just a simplification and you want to draw from lists you got otherwise, simply replace
a,b = random.choices(range(1,11),k=2)
通过
a,b = random.choice(list1), random.choice(list2)
import random
result = []
while True:
a,b = random.choices(range(1,11),k=2) # replace this one as described above
c = a*b
result.append( [a,b,c] )
if c > 50:
break
print(result)
输出:
[[9, 3, 27], [3, 5, 15], [8, 5, 40], [5, 9, 45], [9, 3, 27], [8, 5, 40], [8, 8, 64]]
如果您需要1到10之间的1000个随机整数,请执行以下操作:
If you need 1000 random ints between 1 and 10, do:
random_nums = random.choices(range(1,11),k=1000)
这要快得多,然后循环并附加单个整数1000次.
this if much faster then looping and appending single integers 1000 times.
Doku:
这篇关于建立随机乘法示例列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!