python输入列表中的混合数据类型

时间:2021-06-20 16:26:23

I just started learning python a few days ago and have a quick question I can't find an answer to:

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

How would you ask for items to add to a list while keeping their data type?

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

if i do this:

如果我这样做:

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)

Obviously all the list items are string values. Is there a way to ask for input but keep string, integer, float or whatever data type?

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

2 个解决方案

#1


0  

You could try casting to each variable type:

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

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

#2


0  

You could try with python build in function isnumeric.

你可以尝试在函数isnumeric中使用python build。

Here is what it look like:

这是它的样子:

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)

It only check for integer and string/float.

它只检查整数和字符串/浮点数。

#1


0  

You could try casting to each variable type:

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

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

#2


0  

You could try with python build in function isnumeric.

你可以尝试在函数isnumeric中使用python build。

Here is what it look like:

这是它的样子:

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)

It only check for integer and string/float.

它只检查整数和字符串/浮点数。