如何将嵌套列表中的部分字符串转换为整数?

2 投票
1 回答
548 浏览
提问于 2025-04-18 14:03

我现在正在处理一个嵌套列表,里面有一些数据,我想把这些列表中的某些元素转换成整数。目前这个嵌套列表打印出来是这样的:

def Top5_Bottom5_test():
    with open("Population.txt", "r") as in_file:
        nested = [line.strip().split(',') for line in in_file][1:] #This creates the nested list
        nested[0:][1:] = [int(x) for x in nested[0][1:]] #This is what I'm trying to use to make the numbers in the lists into integers.
        print nested

打印的结果是:

[['Alabama', '126', '79', '17'], ['Alaska', '21', '100', '10'], ['Arizona', '190', '59', '16'], ['Arkansas', '172', '49', '28']....]

但我希望它输出成这样,以便我可以使用冒泡排序:

[['Alabama', 126, 79, 17], ['Alaska', 21, 100, 10], ['Arizona', 190, 59, 16], ['Arkansas', 172, 49, 28]....]

我的最终目标是按每个列表的第二个元素(也就是索引为1的元素)进行降序排序,但我发现如果这些元素还是字符串形式,就无法做到。我也想避免使用sort()和sorted()这两个函数。

1 个回答

2

试试这个:

nested = [line.strip().split(',') for line in in_file][1:]
nested = [line[:1] + [int(x) for x in line[1:]] for line in nested]

这里的窍门是用列表切片来分别处理每一行的第一个元素和其他元素。

撰写回答