Python进程中的多个输入值

2024-10-08 22:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,所以我对编程非常陌生,所以如果我不能用正确的术语提问,请原谅我,但我正在为一个作业编写一个简单的程序,在这个作业中,我要将CGS单位转换为SI单位

例如:

if num == "1": #Gauss --> Tesla
        A=float(raw_input ("Enter value: "))
        print "=", A/(1e4), "T"

有了这个,我一次只能转换一个值。有没有一种方法可以输入多个值(可能用逗号分隔),同时对所有值执行计算,并用转换后的值生成另一个列表?你知道吗


Tags: 程序inputrawif编程作业单位float
2条回答

当然!不过,当你完成时,你必须提供某种“标记”。这个怎么样:

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))

您可以从用户处读入一个以逗号分隔的数字列表(可能会添加空格),然后将其拆分,去掉多余的空格,然后在结果列表上循环,转换每个值,将其放入新列表,最后输出该列表:

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

相关问题 更多 >

    热门问题