首页 > 解决方案 > Python数字数组程序

问题描述

我必须创建一个程序,用户输入询问数组中有多少个数字,您必须从数组中打印这些数字。

例子:

要添加到数组中的值:

12

[14, 64, 62, 21, 91, 25, 75, 86, 13, 87, 39, 48]

我不知道如何在一行中获取所有数字以及如何每次获取不同的数字。这是我到目前为止所拥有的:

import random


x = int(input("How many values to add to the array: "))

b = random.randint(1,99)
c = random.randint(1,99)

for i in range(x):
    twainQuotes = [random.randint(b,c)]

for i in range(x-1):
    print(twainQuotes)

标签: python

解决方案


你可以使用列表理解

if b > c:
    b, c = c, b

twainQuotes = [random.randint(b, c) for _ in range(x)]

打印:_

 print(*twainQuotes, sep='\n')

如果你想使用for循环:

import random


x = int(input("How many values to add to the array: "))

b = random.randint(1,99)
c = random.randint(1,99)

if b > c:
    b, c = c, b

twainQuotes = []
for i in range(x):
    twainQuotes.append(random.randint(b,c))

for e in twainQuotes:
    print(e)

示例输出(对于输入 = 2):

52
65

推荐阅读