【问题标题】:python input mixed data types in listpython在列表中输入混合数据类型
【发布时间】:2018-02-20 02:08:13
【问题描述】:

几天前我刚开始学习python,有一个快速的问题我找不到答案:

您如何要求将项目添加到列表中同时保持其数据类型?

如果我这样做:

def itemType(anyList):
    for i in range(len(anyList)):
        print(type(anyList[i]))

exampleList = []

while True:
    newItem = input('Add item to list? "NO" to end input.)
    if newItem == 'NO':
        break
    else:
        exampleList.append(input())

itemType(exampleList)

显然所有的列表项都是字符串值。有没有办法要求输入但保留字符串、整数、浮点数或任何数据类型?

【问题讨论】:

  • 欢迎来到 SO。输入将始终存储为字符串。计算机如何知道您的2 将用作数字还是字符串?您必须将其转换为您期望输入的数据类型(或使用 try/except 进行转换)。 See also here.快乐编码。
  • 如果您希望用户能够添加任何有效的 Python 文字,请查看 ast.literal_eval;他们的input总是在 Python 3.x 中是一个字符串。但目前还不是很清楚你想在这里实现什么。
  • 没有保留数据类型。用户输入字符串,基本上是信息字节。您可以选择各种方式来解释该信息。使用eval(或更安全地,ast.literal_eval)会将输入字符串解释为 Python 代码(或者在后一种情况下,只有有效的 Python 文字)

标签: python python-3.x list input


【解决方案1】:

您可以尝试转换为每个变量类型:

try:
  newItem = int(newItem)
except ValueError:
  newItem = float(newItem)
except ValueError:
  pass #keep as string

【讨论】:

  • 这不是一个有效的 python 代码。对于字符串,您会得到“在处理上述异常期间,发生了另一个异常”。
【解决方案2】:

您可以尝试使用 python 内置函数 isnumeric。

这是它的样子:

def itemType(anyList):
    for i in range(len(anyList)):
        print(type(anyList[i]))

exampleList = []

while True:
    newItem = input('Add item to list? "NO" to end input.')
    if newItem == 'NO':
        break
    else:
      if(newItem.isnumeric()):
        exampleList.append(int(newItem))
      else:
        exampleList.append(newItem)

itemType(exampleList)

它只检查integer 和string/float。

【讨论】:

  • 您的程序不会将负整数转换为 int
猜你喜欢
  • 2018-05-12
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 2021-10-29
相关资源
最近更新 更多