问题描述
所以我对编程非常陌生,所以如果我不能用正确的术语询问,请原谅我,但是我正在编写一个简单的程序供我转换CGS单位到SI单位
Hi so I'm very very new to programming so please forgive me if I'm not able to ask with the correct jargon, but I'm writing a simple program for an assignment in which I'm to convert CGS units to SI units
例如:
if num == "1": #Gauss --> Tesla
A=float(raw_input ("Enter value: "))
print "=", A/(1e4), "T"
与此同时,我一次只能转换一个值.有没有一种方法可以输入多个值(也许用逗号分隔)并同时对所有值执行计算,并用转换后的值吐出另一个列表?
with this I'm only able to convert one value at a time. Is there a way I can input multiple values, perhaps separated by commas and perform the calculation on all of them simultaneously and spit out another list with the converted values?
推荐答案
您可以从用户那里读取逗号分隔的数字列表(可能添加了空格),然后将其拆分,去除多余的空格并循环在结果列表上,转换每个值,将其放入新列表中,然后最终输出该列表:
You can read in a comma-separated list of numbers from the user (with added whitespace possibly), then split it, strip the excessive white space, and loop over the resulting list, converting each value, putting it in a new list, and then finally outputting that list:
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时,可以使其变得更好,更紧凑:
Later, when you're more fluent in Python, you could make it nicer and more compact:
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)
甚至达到(不推荐)的程度:
or even go as far as (not recommended):
print "RESULT: " + ", ".join(str(float(x.strip()) / 1e4) for x in raw_input("Enter values: ").split(","))
如果您要继续这样做直到用户没有输入任何内容,请像这样包装所有内容:
If you want to keep doing that until the user enters nothing, wrap everything like this:
while True:
raw = raw_input("Enter values: ")
if not raw: # user input was empty
break
... # rest of the code
这篇关于在Python中处理多个输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!