【问题标题】:Are you able to use the "+" in the output of a user input list in Python 3.x? [closed]你能在 Python 3.x 的用户输入列表的输出中使用“+”吗? [关闭]
【发布时间】:2017-11-21 18:06:28
【问题描述】:

所以我试图熟悉 python 中的列表和数组,我只是想知道,你能在 user_input 列表的输出中添加“+”号吗?我知道计算总数并显示列表,但不确定我是否可以这样做。

示例:4 + 5 + 6 + 7 + 8 = 30

【问题讨论】:

  • 不太清楚你在问什么。您是否尝试打印由+ 加号分隔的列表的值?
  • 是的,就是这样。因此,如果用户在显示输出时输入一组数字,是否可以通过“+”来分隔每个输入。
  • 更简单的方法是' + '.join(map(str, your_list))

标签: python python-3.x


【解决方案1】:

如果 Patrick Haugh 说的是正确的,那么我认为你想要的是这样的:

l = []
for i in range(5): # Can be changed to how many numbers you want
    while True:
        try:
            l.append(float(input("Number: ")))
            break
        except ValueError: # If user input is not a number
            print('Must be a number')

for i in l: # Iterates through the list
    print(i, end = '') # end = '' means the printing stays on the same line
    if i != l[-1]: # if i is not equal to the last value in the list
        print(' + ', end = '')
    else:
        print(' = '+str(sum(l))) # prints '=', then the sum of the list

【讨论】:

  • 与其根据其他用户的猜测可能是正确的变化来回答,最好等待让 OP 澄清。
  • 好的,下次会考虑这个。这也是我认为最有可能的问题。在其他情况下,我不会回答这个问题。
猜你喜欢
  • 1970-01-01
  • 2019-03-17
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多