如何对数值字典列表进行排序?

时间:2016-04-26 21:46:43

标签: python list sorting dictionary

我有两个文件,其中包含6000个数值。我只给出了前两个的15个值。

base.txt
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03
2.900000e+03

new2.txt

    0
  100
  200
    1
  101
  201
    2
  102
  202
    3
  103
  203
    4
  104
  204

我想从base.txt值(速度)创建一个新列表,该列表对应于第二个文件的升序。(0,1,2,3,4,5,..) 我的代码到目前为止

import itertools
from operator import itemgetter

vel = [line.strip() for line in open("base.txt", 'r')]
ind = [line.strip() for line in open("new2.txt", 'r')]

print type(vel)
print type(ind)

adict = dict(itertools.izip(ind,vel))

newlist = sorted(adict, key=itemgetter(ind))

我的想法是将文件作为列表读取,创建字典然后尝试对值进行排序,但此代码无效。 我得到了这个

<type 'list'>
<type 'list'>
Traceback (most recent call last):
  File "m1.py", line 11, in <module>
    newlist = sorted(adict, key=itemgetter(ind))
TypeError: string indices must be integers, not list

文件在这里 http://pastebin.com/he1RuSnv

http://pastebin.com/VfXZB4W3

当我尝试CPanda的解决方案时,我得到了

2.900000e+03 0
2.900000e+03 1
2.900000e+03 10
2.900000e+03 100
2.900000e+03 1000
2.900000e+03 1001
2.900000e+03 1002
2.900000e+03 1003
2.900000e+03 1004
2.900000e+03 1005
2.900000e+03 1006
2.900000e+03 1007
2.900000e+03 1008
2.900000e+03 1009
2.900000e+03 101
2.900000e+03 1010
2.900000e+03 1011
2.900000e+03 1012

这不是我想要的,Iwant第二个索引去0,1,2,3,4,5等......

3 个答案:

答案 0 :(得分:2)

要解决错误,您的最后一行sorted应为

newlist = [el[1] for el in sorted(adict.items())]

Sorted从字典中返回键值元组列表。

然后使用列表推导,您可以将有序值提取到newlist

您还可以将最后两行合并为一行:

newlist = [el[1] for el in sorted(itertools.izip(ind,vel))]

答案 1 :(得分:1)

在这种情况下使用字典或关联数组并不是您想要的。字典是无序的,在订单无关紧要时不应使用。

我会使用与此处提到的数据结构不同的数据结构。

Sort a Python dictionary by value

答案 2 :(得分:1)

试试这个

import itertools

with open("base.txt") as fv, open("new2.txt", 'r') as fi:
    vel = (line.strip() for line in fv)
    ind = (int(line.strip()) for line in fi)
    z = itertools.izip(ind, vel) # sort according to ind
    # itertools.izip(vel, ind) # sort according to vel
    for i, v in sorted(z):
        print v,i

# interactive session
l1 = ['2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03',
      '2.900000e+03'] # list(vel)
l2 = [0, 100, 200, 1, 101, 201, 2, 102, 202, 3, 103, 203, 4, 104, 204] # list(ind)
# result
2.900000e+03 0
2.900000e+03 1
2.900000e+03 2
2.900000e+03 3
2.900000e+03 4
2.900000e+03 100
2.900000e+03 101
2.900000e+03 102
2.900000e+03 103
2.900000e+03 104
2.900000e+03 200
2.900000e+03 201
2.900000e+03 202
2.900000e+03 203
2.900000e+03 204
  • 使用生成器表达式而不是列表来提高内存效率和速度。
  • 使用上下文管理器自动close打开文件

请评论,如果它不适合你。

相关问题