如何使用功能更改数据?

时间:2018-12-25 19:35:49

标签: python python-2.7

这些示例之间有什么区别,为什么输出如此?
为什么我们写print Aprint L

def f(N):
    N = N+20

def g():
    A =10
    print A
    f(A)
    print a

#  output 
#  10
#  10

def f(List):
    List[0] = 'A'

def g():
    L = [1,2,3]
    print L 
    f(L)
    print L

#  output 
#  [1,2,3]
#  ['A',2,3]

2 个答案:

答案 0 :(得分:1)

首先,您编写了带有一个参数的函数SoT <- function(df,key) { key_quoted <- enquo(key) df2 <- df %>% dplyr::filter(!!key_quoted > 0) df3 <- janitor::adorn_totals(df2, where = "row") df4 <- tail(df3,1) %>% janitor::adorn_percentages(denominator = "row") %>% janitor::adorn_pct_formatting() return(df4) } SoT(df1, ssd) # respid ssd tea juice vad energy # Total 28.0% 17.3% 21.6% 16.8% 16.3%

f

第二个函数def f(N): N = N+20 ,不带参数,带有局部变量g

A=10

第三个函数def g(): A =10 print A #so prints 10 f(A) # call function `f` passing `10 f(10)` but not printing anything and, not holding return value print a # print `a` values but in the post you have not shown where you declared this `a` 用一个参数,并替换值的f索引(覆盖函数0之上)

f

具有类型def f(List): List[0] = 'A' 的局部变量g的第四个函数L(覆盖函数List之上)

g

答案 1 :(得分:0)

因为当您将数字传递给f()时,它将收到该数字的副本。

但是当您将列表传递给f()时,它将收到对该列表的引用。

看看Difference between call by value and call by reference