2015-02-11 16 views
1

我是python的新手,到目前爲止我的工作還在R上。我想學習我自己 - 對不起,如果這個太基本的問題。在python中的寫入模塊與R相比

The following is R program/function that can output nice plot. 
    # funcomp does some calculations 
    funcomp <- function(x){ 
       z = x ^2 
       k= z + x 
       return(k) 
       } 
    #funplot apply funcomp internally and produce plot. 
    funplot <- function(x){ 
       y <- funcomp(x) 
       plot(x,y) 
       } 

應用功能:

funplot(1:10) 

我試圖做同樣的蟒蛇。

# funcomp does some calculations 
def funcomp(x): 
     z = x ** 2 
     k= z + x 
     return k  

def funplot(x): 
    y = funcomp(x) 
    import matplotlib.pyplot as plt 
    plt.plot(x, y) 

首先我只是把上面的代碼放到python解釋器中。
應用該功能,給我一個錯誤。

funcomp(1:10) 
funplot(1:10) 

我將代碼保存在文件trial.py中並保存到工作目錄。並應用該功能並得到相同的錯誤。

import trial 
trial.funcomp(1:10) 
trial.funplot(1:10) 

這裏有什麼問題,我該如何做到這一點?

編輯: 我提出以下建議下面我試過了,但不能很好地工作:

trial.fumcomp(range(1,11)) 
AttributeError: 'module' object has no attribute 'fumcomp' 

trial.funplot(range(1,11)) 
     2 def funcomp(x): 
----> 3  z = x**2 
     4  k= z + x 
     5  return k 

TypeError: unsupported operand type(s) for ^: 'list' and 'int' 

回答

1

相反的:

1:10 

...用途:

range(1,11) 

進一步請注意,Python不會自動進行向量計算,因此您必須明確地向Python請求d那個。我已經用於funcomp()爲此列表理解(順便說一下,一個問題是,你試圖調用fumcomp(),這並不在你的代碼中存在 - 因此錯誤消息):

# funcomp does some calculations 
def funcomp(x): 
     z = x ** 2 
     k= z + x 
     return k  

def funplot(x): 
    y = [funcomp(xx) for xx in x] 
    import matplotlib.pyplot as plt 
    plt.plot(x, y) 

鑑於這些代碼:

import trial 
import matplotlib.pyplot as plt 
trial.funplot(range(1,11)) 
plt.show() 

...輸出爲:

enter image description here

如果你想Python的是更喜歡R,但是,最好使用numpy,例如給出的代碼在trial2.py

# funcomp does some calculations 
def funcomp(x): 
     z = x ** 2 
     k= z + x 
     return k  

def funplot(x): 
    y = funcomp(x) 
    import matplotlib.pyplot as plt 
    plt.plot(x, y) 

下面的代碼給出了同樣的曲線圖,如圖以上:

import trial2 
import numpy as np 
import matplotlib.pyplot as plt 
trial2.funplot(np.array(range(1,11))) 
plt.show() 

...因爲numpy陣列被計算爲向量,正如在R.

+0

感謝您的快速建議。我仍然收到更多錯誤 - 請參閱我的編輯,謝謝 – jon 2015-02-11 05:14:42