我真的不知道如何用英语解释它但是:
inputText = "John Smith 5"
我想拆分它并将其插入nameArray并将5(字符串)转换为整数.
nameArray = ["John", "Doe", 5]
然后将nameArray放入fullNameArray
fullNameArray = [["John", "Doe", 5], ["John", "Smith", 5]]
解决方法:
在这里使用异常处理和int():
>>> def func(x):
... try:
... return int(x)
... except ValueError:
... return x
...
>>> inputText = "John Smith 5"
>>> spl = [func(x) for x in inputText.split()]
>>> spl
['John', 'Smith', 5]
如果您确定它始终是必须转换的最后一个元素,那么试试这个:
>>> inputText = "John Smith 5"
>>> spl = inputText.split()
>>> spl[-1] = int(spl[-1])
>>> spl
['John', 'Smith', 5]
使用nameArray.append将新列表附加到它:
>>> nameArray = [] #initialize nameArray as an empty list
>>> nameArray.append(["John", "Doe", 5]) #append the first name
>>> spl = [func(x) for x in inputText.split()]
>>> nameArray.append(spl) #append second entry
>>> nameArray
[['John', 'Doe', 5], ['John', 'Smith', 5]]
标签:python,arrays,split,list
来源: https://codeday.me/bug/20190529/1177920.html