繁体   English   中英

如何在 Python 中将输入存储在两个不同的数组中

[英]How to store input in two different arrays in Python

我试图在两个数组中存储 10 个值。 每个阵列 5 个。 如何将用户输入的值存储到数组中?

一个数组用于字符串(产品名称),另一个用于第一个数组中产品的价格。 我试图附加输入但没有成功。

products = []
prices = []

print ("Enter the names of the five products.")
for i in range(5):
    products.append(input())

print ("Enter the prices of the five products.")
for i in range(5):
    prices.append(input())

print (products, end  = "")
print (prices, end  = "")

print ("Press enter to quit ")
quit = input()

预期结果:第一个数组存储输入产品的五个名称,第二个数组有五个价格。

实际结果:程序无法启动。 它几乎立即崩溃。

编辑:

我正在寻找代码来创建这样的输出:

['Apple', 'Micorsoft', 'Sony', 'Oppo', 'Samsung']
['100', '80', '70', '60', '40']

我希望这能让问题更容易理解。

您当前的程序将执行并最终得到以下结果:

Enter the names of the five products.
Enter the prices of the five products.
[<built-in function input>]
[<built-in function input>]

您需要的是一个循环,它将使用input()函数从用户那里获取输入:

products = []
prices = []

print ("Enter the names of the five products.")
for i in range(5):
    products.append(input())

print ("Enter the prices of the five products.")
for i in range(5):
    prices.append(input())

print(products)
print(prices)

输出:

Enter the names of the five products.
Apple
Micorsoft
Sony
Oppo
Samsung
Enter the prices of the five products.
100
80
70
60
40
['Apple', 'Micorsoft', 'Sony', 'Oppo', 'Samsung']
['100', '80', '70', '60', '40']

编辑:

为避免回车\\r

print(products, end  = "")

您可以将程序修改为如下所示:

#!/usr/bin/env python

products = []
prices = []

print ("Enter the names of the five products.")
for i in range(1,6):
    products.append(raw_input(str(i) + " :"))

print ("Enter the prices of the five products.")
for i in range(1,6):
    prices.append(raw_input(str(i) + " :"))

print (products)
print (prices)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM