Py学习  »  Python

(当列表与文本和数字混合时)如何在python中将每个小列表中的数字转换为数字,而不是大列表中的字符串?

Flora • 4 年前 • 1713 次点击  

列表中既有文字也有数字。到目前为止,它们都有“”符号,这意味着它们都是字符串?那么,在python中,如何将每个小列表中的数字转换为数字,而不是大列表中的字符串呢?

这就是我所拥有的:

完整列表=['apple'、'1'、'2']、['banana'、'2'、'3']、['cherry'、'3'、'4']、['downypitch'、'4'、'5']

这就是我想要的: 文本(如apple)的类型为string,而数字(如2)的类型为numeric

新列表=[[apple,1,2],[banana,2,3],[cherry,3,4],[downypitch,4,5]]

这就是我尝试的:

newList = []

for t in wholeList:
    num_part = t[1:]
    
    for j in num_part:
        new_part = int(j)
        newList.append(new_part)

print(newList)

然而,这给了我这样的东西:

[1, 2, 2, 3, 3, 4, 4, 5]

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128579
文章 [ 2 ]  |  最新文章 4 年前
Arthur King
Reply   •   1 楼
Arthur King    4 年前

下面是一种允许数字字符串位于子列表中任意位置且子列表长度任意的方法:

wholeList = [ ['apple','1','2'],['banana','2','3'],['cherry', '3','4'],['downypitch', '4','5'] ]
newList = wholeList[:]
for e in newList:
    for i, x in enumerate(e):
        try:
            e[i] = int(e[i])
        except ValueError:
            pass
print(newList)

输出:

[['apple', 1, 2], ['banana', 2, 3], ['cherry', 3, 4], ['downypitch', 4, 5]]
j1-lee
Reply   •   2 楼
j1-lee    4 年前

根据您的代码,我假设第0个条目仍然是字符串,而第1个、第2个。。。将被转换为整数。

您可以使用以下列表理解:

whole_list = [ ['apple','1','2'],['banana','2','3'],['cherry', '3','4'],['downypitch', '4','5'] ]

new_list = [[sublst[0], *map(int, sublst[1:])] for sublst in whole_list]
print(new_list) # [['apple', 1, 2], ['banana', 2, 3], ['cherry', 3, 4], ['downypitch', 4, 5]]