我必须将整数列表作为输入,然后打印出与每个整数对应的直方图。
Ex: input = [4,9,7]
output: ****
*********
*******
这是我写的代码:
def histogram(list1):
for i in range(len(list1)):
print (list1[i]* "*")
ls=input("Enter the numbers: ")
(histogram(ls))
但是当我输入输入497(我也试过列表(输入))时这不起作用。但是,当我做出以下更改时,它会起作用:
def histogram(list1):
for i in range(len(list1)):
print (list1[i]* "*")
input = [4,9,7]
histogram(input)
如何编写代码以使其根据用户提供的任何输入工作?
答案 0 :(得分:0)
使用python3
(histogram(eval(ls)))
或
import ast
(histogram(ast.literal_eval(ls)))
python2
(histogram(ls))
<强>演示强>
Enter the numbers: [1,2]
*
**
答案 1 :(得分:0)
另一种解决方案:
def histogram(list1):
for i in list1:
print (i * "*")
ls=[]
while True:
cur = input("Enter next number: ")
if (cur == ""):
break;
ls.append(int(cur))
histogram(ls)
答案 2 :(得分:0)
如果您真的希望用户输入Python列表,您可以使用ast.literal_eval
将其转换为真实列表:
import ast
ls = ast.literal_eval(input('Enter the numbers: '))
histogram(ls)
但是,您可以让他们输入用空格分隔的数字,并使用split
:
ls = [int(x) for x in input('Enter the numbers, separated by a space: ').split()]
histogram(ls)
您的histogram
功能也可以缩短为:
def histogram(list1):
for i in list1:
print (i * "*")
如果您使用的是Python 2.x,则需要使用raw_input
代替input
。