我正在尝试生成2个1到10之间的随机数列表,并尝试用户输入他们想要为每个列表生成多少个数字。然后我想弄清楚如何将2个列表添加和相乘。
问题是,我觉得我知道如何让所有这些单独发生,但我似乎无法弄清楚如何使用main()将它们组合在一起
例如:我导入随机然后为随机生成器创建一个空白列表,将数字放入空列表,但我不知道如何创建一个简单的方法,用户输入列表长度的数字。
import random
myList = []
for i in range(1,11):
x = random.randint(1, 10)
myList.append(x)
print(myList)
input("Amount of numbers preferred in a list: ") <---- not sure where to put this and add more code to be part of the generating process.
您可以获取输入,将其转换为int,并使用list comprehension生成列表:
import random
x = int(input("Amount of numbers preferred in a list: "))
l1 = [random.randint(1, 10) for i in range(x)]
您可以对list2执行相同的操作。注意randint()
的哪些边界是包容性的,哪个是排他性的。为此,看看here
为了让您生成两个用户决定的长度列表:
from random import randint
list1 = []
list2 = []
len1 = int(input("What is the length of list1? :"))
len2 = int(input("What is the length of list2? :"))
for _ in range(len1):
list1.append(randint(1,10))
for _ in range(len2):
list2.append(randint(1,10))
print(list1)
print(list2)