2010-02-17 178 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) 

参数拆包:

尝试这样的事情。这是丑陋的。

相关问题