簡體   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