Python分割文本并放入数组中。

4
我不太清楚如何用英语解释,但是:
inputText = "John Smith 5"

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

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

然后将nameArray放入fullNameArray中。
fullNameArray = [["John", "Doe", 5], ["John", "Smith", 5]]
3个回答

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]]

我使用了你的第二段代码,但现在我的问题是我无法像(spl =)那样填充列表,有没有办法将append用于spl以及分割? - Blup Ditzz
@BlupDitzz,你的nameArray必须是一个列表的列表才能得到所需的输出。 - Ashwini Chaudhary
当我只输入一个名称时,我得到了我想要的输出。当我输入第二个名称时,只有第二个名称被打印出来。 - Blup Ditzz
@BlupDitzz 我已经更新了我的代码,请尝试做类似的事情。 - Ashwini Chaudhary

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)

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]]

第三行带有 条件表达式(三元运算符)列表推导式(如果您不熟悉该语法)也可以写成:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接