2016-04-26 94 views
3

我有兩個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等等......

+0

爲什麼不工作?預期的輸出是什麼,你會得到什麼,即任何錯誤? – Francesco

+0

@Francesco已編輯我的帖子,看看! –

回答

2

爲了解決這個錯誤,你的最後一行,在一個與sorted

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

排序返回從字典鍵值元組的列表。

然後用列表解析您提取有序值到您newlist

您還可以在最後兩行合併爲一個:

newlist = [el[1] for el in sorted(itertools.izip(ind,vel))] 
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打開的文件

請評論,如果它不爲你工作。

+1

@C熊貓沒有這不工作。我會粘貼我的文件,所以你可以嘗試自己。 –

+0

你想排序第二個,並根據你想安排的第一個,對不對? –

+0

是的,第二個應該從0開始然後升序,我想安排第一個。 –

相關問題