2015-05-19 85 views
2

創建陣列我有這樣一個帶內容的文件:的Python:從索引列表

1 257.32943114 
10 255.07893867 
100  247.686049588 
1000 248.560238357 
101  250.673715233 
102  250.150281581 
103  247.076694596 
104  257.491337952 
105  250.804702983 
106  252.043717069 
107  253.786482488 
108  255.588547067 
109  251.253294801 
... 

我想要做的就是創建從這個名單在第一列的索引數量的數組。例如,數組的第一個元素將是257.32943114,對應於列表中的1,數組的第109個元素將是251.253294801,對應於列表中的數字109,依此類推。我如何在Python中實現這一點?

+1

那麼沒有顯式索引的值如何?像'[5]'的價值是什麼? – CoryKramer

+2

字典在這裏可能工作得很好 – Ryan

+0

你是什麼意思的「索引列表」? – farhawa

回答

1

如果你堅持使用列表,這裏是另一個更Python的解決方案:

with open('test.in', 'r') as f: 
    r = [] 
    map(lambda (a,b): [0, [r.append(0) for i in xrange(a - len(r))]] and r.append(b), sorted([(int(l.split(' ')[0]), float(l.split(' ')[-1])) for l in f], key=lambda (a,b): a)) 

而且r是你在找什麼。

+0

感謝很多@ skies457運行此解決方案並打印r後,數組的第一個元素爲0.我認爲它來自r.append(0)。我試圖改變/刪除0無濟於事。你知道一種方法,我可以刪除0作爲數組的第一個元素? – Amanda

+0

@Amanda我假設索引從0開始....你可以簡單地取r = r [1:],也就是說,除了第一個以外,所有項都保留在r中。 – skies457

1

可能是你想要一本字典,而不是一個名單,但如果你想有一個清單:

def insert_and_extend(lst, location, value): 
    if len(lst) <= location: 
     lst.extend([None] * (location - len(lst) + 1)) 
    lst[location] = value 

mylist = [] 
insert_and_extend(mylist, 4, 'a') 
insert_and_extend(mylist, 1, 'b') 
insert_and_extend(mylist, 5, 'c') 
print mylist 

要做到這一點作爲字典:

dict = {} 
dict[4] = 'a' 
dict[1] = 'b' 
dict[5] = 'c' 
print dict 
+0

我同意。我想你在找一本「字典」。如果你只使用第一個數字作爲索引,那麼一個「字典」就是完美的。查看[這段代碼片段](http://pastebin.com/ASkxKZTh)如果一個字典解決方案對你來說很有意義 –

+0

您好MK,感謝您的評論。我不知道Python有這個字典。你能給我一個想法如何實現它嗎?再次感謝。 – Amanda

1

分隔符:可以使用Tab鍵或空格在分割線上

file = open(location, 'r') 
dictionary = {} 
for line in file.readlines(): 
    aux = line.split(' ') #separator 
    dictionary[aux[0]] = aux[1] 
print dictionary 

如果你有像'257.32943114 \ n'這樣的值,你可以使用instead dictionary [aux [0 ]] = aux [1] [: - 1]來避開新行的字符。

+0

從這個問題看,整個空間看起來並不相同。我認爲這是一個好主意,使用're'模塊進行分割:'aux = re.split(r'+',line)' –

+0

Hi @Carlos,謝謝你的幫助。當我'打印字典[aux [0]]'時,我只得到第二列中的數字,但它沒有排序。我想根據第一列中的相應索引對第二列中的數字進行排序。請,我怎樣才能做到這一點? – Amanda

+0

我使用Tab鍵而不是空格,它的工作原理...也許一切都取決於文件格式... TY爲您的支持@AlokShankar –