【问题标题】:How to make only some strings of nested lists into integers?如何仅将一些嵌套列表字符串转换为整数?
【发布时间】:2014-07-20 21:34:25
【问题描述】:

所以目前我正在尝试使用数据嵌套列表并将这些列表中的一些元素转换为整数。所以现在嵌套列表会打印:

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() 函数。

【问题讨论】:

    标签: python python-2.7 int nested-lists


    【解决方案1】:

    试试这个:

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

    诀窍是使用列表切片分别处理每行中的第一个元素和其余元素。

    【讨论】:

    • 似乎会产生错误“ValueError: invalid literal for int() with base 10: 't'”。
    • @JohnathanScott 我更新了我的答案,如果它仍然失败 - 你确定输入数据看起来像问题中的样本吗?似乎某行中的某个元素(在第一个元素之后)是 not 整数。
    • 我正在导入的 .txt 文件中的第一行在我上面的代码中被忽略了,因为它只是传说中的说法。通常它只是一个文本文件,其中包含 Alabama、1、2、3 Alaska、2、5、3 等...但是我将其拆分为嵌套列表的代码。
    • 好的,你应该提到 :) 。现在已经修好了。
    • 你是圣人,非常感谢! :) 现在才学python,天哪,是不是很沮丧哈哈
    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 2019-04-24
    • 2019-12-14
    • 2021-11-25
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多