2010-02-17 196 views

回答

1

寫一個幫手函數。

這是一個很長的版本,但我相信有一個技巧來壓縮它。

>>> def helper(lst): 
    lst1, lst2 = [], [] 
    for el in lst: 
     lst1.append(el[0]) 
     lst2.append(el[1]) 
    return lst1, lst2 

>>> 
>>> helper([[1,2],[3,4],[5,6]]) 
([1, 3, 5], [2, 4, 6]) 
>>> 

而且添加這個幫手:

def myplot(func, lst, flag): 
    return func(helper(lst), flag) 

,並調用它像這樣:

myplot(plt.plot, [[1,2],[3,4],[5,6]], 'ro') 

另外,您可以將函數添加到一個已經實例化的對象。

54

你可以做這樣的事情:

a=[[1,2],[3,3],[4,4],[5,2]] 
plt.plot(*zip(*a)) 

不幸的是,你不能再通過 'RO'。您必須傳遞標記和線條樣式值作爲關鍵字參數:

a=[[1,2],[3,3],[4,4],[5,2]] 
plt.plot(*zip(*a), marker='o', color='r', ls='') 

我使用的技巧是unpacking argument lists

+6

我通常使用'plt.plot(* np.transpose(a))'(我稱之爲'import numpy as np'),這相當於您的建議。 – 2012-05-23 01:44:03

9

如果您使用numpy的數組,你可以通過軸提取:

a = array([[1,2],[3,3],[4,4],[5,2]]) 
plot(a[:,0], a[:,1], 'ro') 

對於列表或列出你需要一些幫助,比如:

a = [[1,2],[3,3],[4,4],[5,2]] 
plot(*sum(a, []), marker='o', color='r') 
8

列表內涵

我強烈建議列表解析的自由應用。它們不僅簡潔而且功能強大,它們傾向於使代碼非常易讀。應避免

list_of_lists = [[1,2],[3,3],[4,4],[5,2]]  
x_list = [x for [x, y] in list_of_lists] 
y_list = [y for [x, y] in list_of_lists] 

plt.plot(x_list, y_list) 

參數拆包:

嘗試這樣的事情。這是醜陋的。

相關問題