【问题标题】:How do I store user input WITHOUT using a list in Python?如何在不使用 Python 列表的情况下存储用户输入?
【发布时间】:2019-09-21 02:03:00
【问题描述】:

我目前正在尝试将用户输入存储为整数,而不将它们附加到列表或根本不创建列表。

首先,我尝试为每个输入使用 5 个独立变量(下面的代码),当运行此代码时,它给出了以下内容:

您输入的华氏度为 (1, 2, 3, 4, 5)

我将如何删除这些括号?

firstFahr = int(input("Please enter a Fahrenheit temperature: "))
secondFahr = int(input("Please enter a Fahrenheit temperature: "))
thirdFahr = int(input("Please enter a third Fahrenheit temperature: "))
fourthFahr = int(input("PLease enter a fourth Fahrenheit temperature: "))
fifthFahr = int(input("Please enter a fifth Fahrenheit temperature: "))

enteredFahrs = firstFahr, secondFahr, thirdFahr, fourthFahr, fifthFahr


print("The fahrenheits you entered are", enteredFahrs)

感谢您提前提供的任何帮助,如果这似乎是一个菜鸟问题,我们深表歉意,因为我对 Python 还很陌生。

【问题讨论】:

  • 为什么要避免列出清单?在这里,列表实际上是最明智的使用方法。 (请注意,在您粘贴的代码中,没有列表 - 只是一个元组。)
  • 通常用于存储用户输入,使用常见的数据结构,如列表、元组、集合或字典。目前,您将输入存储为元组。我认为使用列表存储变量没有任何缺点。您可以创建这样的列表enteredFahrs = [firstFahr, secondFahr, thirdFahr, fourthFahr, fifthFahr]

标签: python string input int output


【解决方案1】:

这个怎么样:

prompts = ('first', 'second', 'third', 'fourth', 'fifth')
entered_fahrs = tuple(
   int(input(f'Please enter a {p} Fahrenheit temperature: '))
   for p in prompts
)
print(f'The Fahrenheits you entered are: {", ".join(str(f) for f in entered_fahrs)}')

如果你真的,真的想避免序列,那么你可以做一个简单的解包:

first_fahr, second_fahr, third_fahr, fourth_fahr, fifth_fahr = entered_fahrs

【讨论】:

  • ...那“没有清单”呢?
  • @Austin 我怀疑 OP 想要什么和他们说他们想要什么是两件不同的事情。
  • 我不这么认为;但是使用列表绝对是要走的路。
  • @Austin OP 对这个话题保持沉默,但为了更好地衡量,我已经展示了如何打开包装以避免令人讨厌的列表。
  • 我会在这里插话:我不想要一个列表。我正在做的事情的规范,不管你信不信,都没有指定任何列表……我已经使用列表完成了程序,这很简单,FWIW。感谢您的回答:)
【解决方案2】:

这应该可以解决您的问题:

firstFahr = int(input("Please enter a Fahrenheit temperature: "))
secondFahr = int(input("Please enter a Fahrenheit temperature: "))
thirdFahr = int(input("Please enter a third Fahrenheit temperature: "))
fourthFahr = int(input("PLease enter a fourth Fahrenheit temperature: "))
fifthFahr = int(input("Please enter a fifth Fahrenheit temperature: "))

print("The fahrenheits you entered are", firstFahr, secondFahr, thirdFahr, fourthFahr, fifthFahr)

没有任何列表(也没有括号)。

【讨论】:

    【解决方案3】:

    我怀疑这是您真正被要求做的事情,但另一种方法是使用生成器表达式来避免完全存储变量。

    user_inputs = (
       int(input(f'Please enter a {p} Fahrenheit temperature: '))
       for p in ('first', 'second', 'third', 'fourth', 'fifth')
    )
    
    print("The fahrenheits you entered are", *user_inputs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      相关资源
      最近更新 更多