【问题标题】:How can I input multiple values in one line? [duplicate]如何在一行中输入多个值? [复制]
【发布时间】: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

标签: python input


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 谢谢。它有帮助。
【解决方案2】:

这就是你想要的;输入的数字必须用逗号隔开:

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

【讨论】:

  • 我试过了,但输出看起来不像 exp。 a:8 b:5 c:6 d:4 e:0.1。我刚得到1、2、3、4。
  • 好吧,如果您希望它完全采用这种格式,那么它并不难,将编辑该问题。
  • 抱歉这个问题。我是 python 新手,所以我不知道具体怎么做。那么你能告诉我输入应该是什么样子吗?谢谢。
  • @NewInThis 我的意思是我将编辑我的答案。我刚刚更新了它,看看能不能回答你的问题。
  • 是的,它有帮助。谢谢。
猜你喜欢
  • 2021-11-19
  • 1970-01-01
  • 2018-08-22
  • 2017-07-13
  • 2011-04-19
  • 2018-07-10
  • 2020-03-09
  • 2022-11-29
  • 2021-11-15
相关资源
最近更新 更多