【发布时间】:2020-11-06 07:29:39
【问题描述】:
如何在一行中输入多个值? 输出应该类似于 a:8 b:5 c:6 d:4 e:0.1
我已经尝试过这个输入:
a, b, c, d, e = int(input(' '.format(a:, b:, c:, d:, e:)))
但这没有用。
【问题讨论】:
-
查看用户
pp_发布的答案 -
只做 a,b,c,d=1,2,3,4
如何在一行中输入多个值? 输出应该类似于 a:8 b:5 c:6 d:4 e:0.1
我已经尝试过这个输入:
a, b, c, d, e = int(input(' '.format(a:, b:, c:, d:, e:)))
但这没有用。
【问题讨论】:
pp_发布的答案
你可以这样做:
a, b, c, d, e = input("Insert the 5 values: ").split()
print(f"a: {a}\nb: {b}\nc: {c}\nd: {d}\ne: {e}")
输入:
1 2 3 4 5
输出:
a: 1
b: 2
c: 3
d: 4
e: 5
【讨论】:
这就是你想要的;输入的数字必须用逗号隔开:
a, b, c, d = (int(num) for num in input().split(','))
解释:
gotten_input = input('Enter a list of numbers separated by commas: ')
# user enters '1, 2, 3, 40, 500'
split_input_list = gotten_input.split(',')
# contains ['1', ' 2', ' 3', ' 40', ' 500']
numbers_tuple = (int(num) for num in split_input_list)
# contains (1, 2, 3, 40, 500)
# now the tuple's values are ready to assign
a, b, c, d, e = numbers_tuple
# now a=1, b=2, c=3, d=40, e=500
但是如果输入一个浮点数,int 不会做你想做的事;如果你想要floats 和ints 的混合,你的逻辑必须变得更复杂一点:
a, b, c, d, e = (float(num) if '.' in num else int(num) for num in input().split(','))
# uses the Ternary operator to determine if the numbers should be converted to float or int
要获得您要求的确切输出格式,您可以将字符串格式化为其他答案的格式,而不是没有换行符:
print(f"a:{a} b:{b} c:{c} d:{d} e:{e}")
或者:
print("a:{} b:{} c:{} d:{} e:{}".format(*(int(num) for num in input().split(','))))
# The * unpacks the tuple into a list of arguments to send to format()
【讨论】: