Python将文本拆分并放入数组中

时间:2013-06-16 06:54:07

标签: python arrays list split

我真的不知道怎么用英语来解释它,但是:

inputText = "John Smith 5"

我想将其拆分并将其插入nameArray并将5(字符串)转换为整数。

nameArray = ["John", "Doe", 5]

然后将nameArray放到fullNameArray

fullNameArray = [["John", "Doe", 5], ["John", "Smith", 5]]

3 个答案:

答案 0 :(得分:3)

在此处使用异常处理和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]]

答案 1 :(得分:2)

您正在寻找nameArray = inputText.split()

以下代码适用于字符串中的任何数字

所以假设输入位于名为inputTextList的列表中:

fullNameArray = []
for inputText in inputTextList:
    nameArray = inputText.split()
    nameArray = [int(x) if x.isdigit() else x for x in nameArray]
    fullNameArray.append(nameArray)

答案 2 :(得分:1)

>>> fullnameArray = [["John", "Doe", 5]] 
>>> inputText = "John Smith 5"
>>> fullnameArray.append([int(i) if i.isdigit() else i for i in inputText.split()])
>>> fullnameArray
[['John', 'Doe', 5], ['John', 'Smith', 5]]

conditional expression ("ternary operator")list comprehension的第三行(如果您不熟悉该语法)也可以写成:

nameArray = []
for i in inputText.split():
    if i.isdigit():
        nameArray.append(int(i))
    else:
        nameArray.append(i)
fullnameArray.append(sublist)
相关问题