将列表中的列转换为数字,保持其他列不变

时间:2014-08-07 16:16:40

标签: python list

我有一个如下列表。我想将列表中的数字替换为整数,该整数当前采用单引号'8'中的字符串形式。

一旦用号码替换,想要在列表中对该号码进行排序。

[['8', '/opt/sis/local/ad'], ['327912', '/opt/sis/local/bd'], ['20180', '/opt/sis/local/cd'], ['40', '/opt/sis/local/dd'], ['1464', '/opt/sis/local/ed'], ['32', '/opt/sis/local/fd'], ['3803092', '/opt/sis/local/gd'], ['34930968', '/opt/sis/local/hd'], ['3095500', '/opt/sis/local/id-inventory']]

我这样做是为了找到占用更多空间的前4个目录。

2 个答案:

答案 0 :(得分:3)

lst = [[int(x[0]), x[1]] for x in data]
lst.sort(key=lambda x: x[0])

答案 1 :(得分:0)

首先转置它(即将行更改为列)

columns = zip(*my_2d_list)

然后更改第一列

columns[0] = [int(n) for n in columns[0]]

最后将其拉回原始列表

my_2d_list = zip(*columns)

然后只需对其进行排序

sorted(my_2d_list,reverse=True)[:4] # 4 biggest numbers ... at least it should be
然而,只做

可能更明智
 sorted(my_original_list,key=lambda x: int(x[0]),reverse=True)[:4]

如@PadraicCunningham(和jon sharp)所述