所以目前我正在尝试获取一个包含数据的嵌套列表,并将这些列表的一些元素转换为整数。所以现在嵌套列表打印如下:
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() 和排序() 函数。
最佳答案
试试这个:
nested = [line.strip().split(',') for line in in_file][1:]
nested = [line[:1] + [int(x) for x in line[1:]] for line in nested]
技巧是使用列表切片分别处理每行中的第一个元素和其余元素。
关于python - 如何仅将嵌套列表的某些字符串转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24855126/