0
從下面的代碼中,我得到:類型錯誤:無法通過類型「列表」項目轉換成int
x = list(input("Input a list of integers, seperated by a comma:"))
def histogram(x):
for y in x:
print("*"*x)
histogram(x)
從下面的代碼中,我得到:類型錯誤:無法通過類型「列表」項目轉換成int
x = list(input("Input a list of integers, seperated by a comma:"))
def histogram(x):
for y in x:
print("*"*x)
histogram(x)
的非INT繁衍序列我假設你想要的東西,看起來會有點像:
>>> histogram('1,5,1,3')
*
*****
*
***
你必須改變一些東西,然後。
首先是,x = list(input())
會給你在你輸入的字母/字符的列表。所以list('1,2,3')
將產生['1', ',', '2', ',', '3']
,我相信你不想處理逗號。
相反,您應該使用string.split(',')
分割每個逗號。取決於你想如何做到這一點,你可以在你的函數內部(如我下面所做的那樣)或直接輸出,以便函數期望一串數字串。
我說「數字串列表」,因爲input
返回一個字符串,所以即使輸入數字,它也會給你STRINGS。您必須確保明確投射爲int
以便能夠乘以'*'
。
最後,你的問題的實際答案?您正在致電print("*"*x)
。我想你的意思是print("*"*y)
或更準確地說,print("*"*int(y))
。
下面是我認爲是工作的代碼,但同樣,我不知道你的期望輸出實際上是什麼。
>>> x = input("Please enter comma separated list of numbers: ")
Please enter comma separated list of numbers:
>>> x = input("Please enter comma separated list of numbers: ")
Please enter comma separated list of numbers: 1,2,3,4,5,6,1,2
>>> def histogram(x):
for y in x.split(','):
print("*"*int(y))
>>> histogram(x)
*
**
***
****
*****
******
*
**