嗨所以我对编程很新,所以请原谅我,如果我不能用正确的术语问,但是我正在编写一个简单的程序来完成我要转换CGS单元的作业到SI单位
例如:
if num == "1": #Gauss --> Tesla
A=float(raw_input ("Enter value: "))
print "=", A/(1e4), "T"
这个我只能一次转换一个值。有没有办法可以输入多个值,可能用逗号分隔并同时对所有值进行计算,然后用转换后的值吐出另一个列表?
答案 0 :(得分:3)
您可以从用户读取逗号分隔的数字列表(可能添加空格),然后将其拆分,去除多余的空白区域,并在结果列表上循环,转换每个值,将其放入新的列表,然后最终输出该列表:
raw = raw_input("Enter values: ")
inputs = raw.split(",")
results = []
for i in inputs:
num = float(i.strip())
converted = num / 1e4
results.append(converted)
outputs = []
for i in results:
outputs.append(str(i)) # convert to string
print "RESULT: " + ", ".join(outputs)
后来,当你对Python更加流利时,你可以让它变得更好,更紧凑:
inputs = [float(x.strip()) for x in raw_input("Enter values: ").split(",")]
results = [x / 1e4 for x in inputs]
print "RESULT: " + ", ".join(str(x) for x in results)
甚至可以推荐(不推荐):
print "RESULT: " + ", ".join(str(float(x.strip()) / 1e4) for x in raw_input("Enter values: ").split(","))
如果您想继续这样做,直到用户输入任何内容,请包装如下所示:
while True:
raw = raw_input("Enter values: ")
if not raw: # user input was empty
break
... # rest of the code
答案 1 :(得分:1)
当然!你必须提供某种"标记"但是,当你完成的时候。怎么样:
if num == '1':
lst_of_nums = []
while True: # infinite loops are good for "do this until I say not to" things
new_num = raw_input("Enter value: ")
if not new_num.isdigit():
break
# if the input is anything other than a number, break out of the loop
# this allows for things like the empty string as well as "END" etc
else:
lst_of_nums.append(float(new_num))
# otherwise, add it to the list.
results = []
for num in lst_of_nums:
results.append(num/1e4)
# this is more tersely communicated as:
# results = [num/1e4 for num in lst_of_nums]
# but list comprehensions may still be beyond you.
如果您尝试输入一串以逗号分隔的值,请尝试:
numbers_in = raw_input("Enter values, separated by commas\n>> ")
results = [float(num)/1e4 for num in numbers_in.split(',')]
如果你想列出这两个,那么,构建一个字典!
numbers_in = raw_input("Enter values, separated by commas\n>> ")
results = {float(num):float(num)/1e4 for num in numbers_in.split(',')}
for CGS,SI in results.items():
print "%.5f = %.5fT" % (CGS, SI)
# replaced in later versions of python with:
# print("{} = {}T".format(CGS,SI))