简体   繁体   English

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

[英](When list mix with text & numbers) How to convert numbers in each small list into numeric instead of string within that big list in python?

The list is mixed with both text and numbers.该列表混合了文本和数字。 And so far they all have ' ' symbol, means they are all string?到目前为止他们都有''符号,意味着他们都是字符串? So how to convert numbers in each small list into numeric instead of string within that big list in python?那么如何将每个小列表中的数字转换为数字而不是 python 中那个大列表中的字符串?

This is what I have:这就是我所拥有的:

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

This is what I want: text such as apple have type string, while the numbers such as 2 have type numeric这就是我想要的:文本如 apple 的类型为字符串,而数字如 2 的类型为数字

newList = [ [apple,1,2],[banana,2,3],[cherry, 3,4],[downypitch, 4,5]] newList = [ [苹果,1,2],[香蕉,2,3],[樱桃,3,4],[低音,4,5]]

This is what I tried:这是我试过的:

newList = []

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

print(newList)

However, this gives me something like this:然而,这给了我这样的东西:

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

Based on your code, I am assuming that 0-th entry remains to be string, while 1st, 2nd, ... are to be converted into integers.根据您的代码,我假设第 0 个条目仍然是字符串,而第 1、2、... 将被转换为整数。

You can use list comprehension as follows:您可以按如下方式使用列表理解:

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

Here's an approach that allows for the number strings being anywhere in the sublists and for the sublists to be of any length:这是一种允许数字字符串位于子列表中的任何位置并且子列表具有任意长度的方法:

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)

Output: Output:

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

If you have mixture of text and number, this would be the best solution如果您混合使用文本和数字,这将是最佳解决方案

Because string can appear at any location因为字符串可以出现在任何位置

wholeList = [ ['apple','1','2'],['2','banana', '3'],['3','4', 'cherry'],['downypitch', '4','5'] ]
newlist = []
for sublist in wholeList:
   temp = []
   for string in sublist:
       try:
           temp.append(int(string))
       except:
            temp.append(string)
   newlist.append(temp)
print(newlist)
# op: wholeList = [ ['apple','1','2'],['2','banana', '3'],['3','4', 'cherry'],['downypitch', '4','5'] ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM