diff options
-rw-r--r-- | .github/CODEOWNERS | 2 | ||||
-rw-r--r-- | de-de/rust-de.html.markdown | 2 | ||||
-rw-r--r-- | de-de/vim-de.html.markdown | 1 | ||||
-rw-r--r-- | es-es/rust-es.html.markdown | 2 | ||||
-rw-r--r-- | fr-fr/rust-fr.html.markdown | 2 | ||||
-rw-r--r-- | fr-fr/set-theory-fr.html.markdown | 10 | ||||
-rw-r--r-- | it-it/rust-it.html.markdown | 2 | ||||
-rw-r--r-- | mongodb.html.markdown | 6 | ||||
-rw-r--r-- | pt-br/r-pt.html.markdown | 786 | ||||
-rw-r--r-- | pt-br/rust-pt.html.markdown | 2 | ||||
-rw-r--r-- | r.html.markdown | 289 | ||||
-rw-r--r-- | ru-ru/rust-ru.html.markdown | 2 | ||||
-rw-r--r-- | uk-ua/rust-ua.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/python-cn.html.markdown | 739 | ||||
-rw-r--r-- | zh-cn/rust-cn.html.markdown | 2 |
15 files changed, 1525 insertions, 324 deletions
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 6c1efe0d..7bc421a7 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4,3 +4,5 @@ /zh-cn/ @geoffliu @imba-tjd
/zh-tw/ @geoffliu @imba-tjd
/ko-kr/ @justin-themedium
+/pt-pt/ @mribeirodantas
+/pt-br/ @mribeirodantas
diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown index 02bb460a..6208db68 100644 --- a/de-de/rust-de.html.markdown +++ b/de-de/rust-de.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: diff --git a/de-de/vim-de.html.markdown b/de-de/vim-de.html.markdown index 8abf9a14..93fd9773 100644 --- a/de-de/vim-de.html.markdown +++ b/de-de/vim-de.html.markdown @@ -21,7 +21,6 @@ einer Datei. ``` vim <filename> # Öffne <filename> in Vim - :help <topic> # Open up built-in help docs about <topic> if any exists :help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn # es existiert :q # Schließe vim diff --git a/es-es/rust-es.html.markdown b/es-es/rust-es.html.markdown index dc48abf5..b0a3873c 100644 --- a/es-es/rust-es.html.markdown +++ b/es-es/rust-es.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown index a61f78be..c81dd1d6 100644 --- a/fr-fr/rust-fr.html.markdown +++ b/fr-fr/rust-fr.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: diff --git a/fr-fr/set-theory-fr.html.markdown b/fr-fr/set-theory-fr.html.markdown index 50a4ea30..dad8fa7a 100644 --- a/fr-fr/set-theory-fr.html.markdown +++ b/fr-fr/set-theory-fr.html.markdown @@ -1,11 +1,11 @@ -``` --- -category: tool -lang: fr-fr +category: Algorithms & Data Structures name: Set theory +lang: fr-fr contributors: - - ["kieutrang", "https://github.com/kieutrang1729"] + - ["kieutrang", "https://github.com/kieutrang1729"] --- + La théorie des ensembles est une branche des mathématiques qui étudie les ensembles, leurs opérations et leurs propriétés. * Un ensemble est une collection d'éléments disjoints. @@ -130,5 +130,3 @@ Le produit cartésien de deux ensembles `A` et `B` est l'ensemble contenant tous ``` A × B = { (x, y) | x ∈ A, y ∈ B } ``` - -``` diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown index df4d6279..acb8b8ba 100644 --- a/it-it/rust-it.html.markdown +++ b/it-it/rust-it.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["Carlo Milanesi", "http://github.com/carlomilanesi"] lang: it-it diff --git a/mongodb.html.markdown b/mongodb.html.markdown index 959b57d0..306f361c 100644 --- a/mongodb.html.markdown +++ b/mongodb.html.markdown @@ -256,7 +256,7 @@ db.engineers.find({ $gt: { age: 25 }}) db.engineers.find({ $gte: { age: 25 }}) // Find all less than or less than equal to some condition -db.engineers.find({ $lte: { age: 25 }}) +db.engineers.find({ $lt: { age: 25 }}) db.engineers.find({ $lte: { age: 25 }}) // Find all equal or not equal to @@ -293,7 +293,7 @@ db.engineers.find({ $not: { // Must match none of the query conditions db.engineers.find({ $nor [ - gender: 'Female, + gender: 'Female', age: { $gte: 18 } @@ -400,6 +400,6 @@ features, I would look at - Aggregation - useful for creating advanced queries to be executed by the database -- Idexing allows for caching, which allows for much faster execution of queries +- Indexing allows for caching, which allows for much faster execution of queries - Sharding allows for horizontal data scaling and distribution between multiple machines. diff --git a/pt-br/r-pt.html.markdown b/pt-br/r-pt.html.markdown new file mode 100644 index 00000000..eeaa4eab --- /dev/null +++ b/pt-br/r-pt.html.markdown @@ -0,0 +1,786 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] + - ["kalinn", "http://github.com/kalinn"] +translators: + - ["Marcel Ribeiro-Dantas", "http://github.com/mribeirodantas"] +lang: pt-br +filename: learnr.r +--- + +R é uma linguagem de programação estatística. Ela tem muitas bibliotecas para carregar e limpar conjuntos de dados, executar análises estatísticas e produzir gráficos. Você também pode executar comandos do `R` dentro de um documento LaTeX. + +```r + +# Comentários começam com o símbolo de Cerquilha, também conhecido como +# jogo da velha + +# Não existe um símbolo especial para comentários em várias linhas +# mas você pode escrever várias linhas de comentários adicionando a +# cerquilha (#) ao início de cada uma delas. + +# No Windows e Linux, você pode usar CTRL-ENTER para executar uma linha. +# No MacOS, o equivalente é COMMAND-ENTER + + + +############################################################################# +# Coisas que você pode fazer sem entender nada sobre programação +############################################################################# + +# Nesta seção, mostramos algumas das coisas legais que você pode fazer em +# R sem entender nada de programação. Não se preocupe em entender tudo o +# que o código faz. Apenas aproveite! + +data() # navegue pelos conjuntos de dados pré-carregados +data(rivers) # carregue este: "Comprimentos dos principais rios norte-americanos" +ls() # observe que "rivers" apareceu na área de trabalho (workspace) +head(rivers) # dê uma espiada no conjunto de dados +# 735 320 325 392 524 450 + +length(rivers) # quantos rios foram medidos? +# 141 +summary(rivers) # consulte um sumário de estatísticas básicas +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 + +# faça um diagrama de ramos e folhas (uma visualização de dados semelhante a um histograma) +stem(rivers) + +# A vírgula está 2 dígito(s) à direita do símbolo | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + +stem(log(rivers)) # Observe que os dados não são normais nem log-normais! +# Tome isso, fundamentalistas da curva normal! + +# O ponto decimal está 1 dígito(s) à esquerda do símbolo | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + +# faça um histograma: +hist(rivers, col="#333333", border="white", breaks=25) # brinque com estes parâmetros +hist(log(rivers), col="#333333", border="white", breaks=25) # você fará mais gráficos mais tarde + +# Aqui está outro conjunto de dados que vem pré-carregado. O R tem toneladas deles. +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Ano", + main="Número de descobertas importantes por ano") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Ano", + main="Número de descobertas importantes por ano") + +# Em vez de deixar a ordenação padrão (por ano), +# também podemos ordenar para ver o que é mais comum: +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) +# +# O ponto decimal está no símbolo | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +# 12 +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + +# Role um dado algumas vezes +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 +# Seus números serão diferentes dos meus, a menos que definamos a mesma semente aleatória com o set.seed + +# Obtenha 9 números de forma aleatória a partir de uma distribuição normal +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + +################################################## +# Tipos de dados e aritmética básica +################################################## + +# Agora para a parte orientada a programação do tutorial. +# Nesta seção você conhecerá os tipos de dados importantes do R: +# integers, numerics, characters, logicals, e factors. +# Existem outros, mas estes são o mínimo que você precisa para +# iniciar. + +# INTEGERS +# Os inteiros de armazenamento longo são escritos com L +5L # 5 +class(5L) # "integer" +# (Experimente ?class para obter mais informações sobre a função class().) +# Em R, todo e qualquer valor, como 5L, é considerado um vetor de comprimento 1 +length(5L) # 1 +# Você pode ter um vetor inteiro com comprimento > 1 também: +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + +# NUMERICS +# Um "numeric" é um número de ponto flutuante de precisão dupla +5 # 5 +class(5) # "numeric" +# De novo, tudo em R é um vetor; +# você pode fazer um vetor numérico com mais de um elemento +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# Você também pode usar a notação científica +5e4 # 50000 +6.02e23 # Número de Avogadro +1.6e-35 # Comprimento de Planck +# Você também pode ter números infinitamente grandes ou pequenos +class(Inf) # "numeric" +class(-Inf) # "numeric" +# Você pode usar "Inf", por exemplo, em integrate(dnorm, 3, Inf) +# isso evita as tabelas de escores-Z. + +# ARITMÉTICA BÁSICA +# Você pode fazer aritmética com números +# Fazer aritmética com uma mistura de números inteiros (integers) e com +# ponto flutuante (numeric) resulta em um numeric +10L + 66L # 76 # integer mais integer resulta em integer +53.2 - 4 # 49.2 # numeric menos numeric resulta em numeric +2.0 * 2L # 4 # numeric vezes integer resulta em numeric +3L / 4 # 0.75 # integer dividido por numeric resulta em numeric +3 %% 2 # 1 # o resto de dois numeric é um outro numeric +# Aritmética ilegal produz um "não-é-um-número" (do inglês Not-a-Number): +0 / 0 # NaN +class(NaN) # "numeric" +# Você pode fazer aritmética em dois vetores com comprimento maior que 1, +# desde que o comprimento do vetor maior seja um múltiplo inteiro do menor +c(1,2,3) + c(1,2,3) # 2 4 6 +# Como um único número é um vetor de comprimento um, escalares são aplicados +# elemento a elemento com relação a vetores +(4 * c(1,2,3) - 2) / 2 # 1 3 5 +# Exceto para escalares, tenha cuidado ao realizar aritmética em vetores com +# comprimentos diferentes. Embora possa ser feito, +c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 +# ter comprimentos iguais é uma prática melhor e mais fácil de ler +c(1,2,3,1,2,3) * c(1,2,1,2,1,2) + +# CHARACTERS +# Não há diferença entre strings e caracteres em R +"Horatio" # "Horatio" +class("Horatio") # "character" +class('H') # "character" +# São ambos vetores de caracteres de comprimento 1 +# Aqui está um mais longo: +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# Você pode utilizar expressões regulares (regex) em vetores de caracteres: +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +# R tem vários vetores de caracteres embutidos: +letters +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + +# LOGICALS +# Em R, um "logical" é um booleano +class(TRUE) # "logical" +class(FALSE) # "logical" +# O comportamento deles é normal +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# Dados ausentes (NA) são logical, também +class(NA) # "logical" +# Use | e & para operações lógicas. +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# Aplicar | e & a vetores retorna operações lógicas elemento a elemento +c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE +c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE +# Você pode testar se x é TRUE +isTRUE(TRUE) # TRUE +# Aqui obtemos um vetor logical com muitos elementos: +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE + +# FACTORS +# A classe factor é para dados categóricos +# Os fatores podem ser ordenados (como as avaliações de crianças) ou +# não ordenados (como as cores) +factor(c("azul", "azul", "verde", NA, "azul")) +# azul azul verde <NA> azul +# Levels: azul verde +# Os "levels" são os valores que os dados categóricos podem assumir +# Observe que os dados ausentes não entram nos levels +levels(factor(c("verde", "verde", "azul", NA, "azul"))) # "azul" "verde" +# Se um vetor de factor tem comprimento 1, seus levels também terão comprimento 1 +length(factor("green")) # 1 +length(levels(factor("green"))) # 1 +# Os fatores são comumente vistos em data frames, uma estrutura de dados que abordaremos +# mais tarde +data(infert) # "Infertilidade após aborto espontâneo e induzido" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + +# NULL +# "NULL" é um valor estranho; use-o para "apagar" um vetor +class(NULL) # NULL +parakeet = c("bico", "penas", "asas", "olhos") +parakeet +# [1] "bico" "penas" "asas" "olhos" +parakeet <- NULL +parakeet +# NULL + +# COERÇÃO DE TIPO +# Coerção de tipo é quando você força um valor a assumir um tipo diferente +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# Se você colocar elementos de diferentes tipos em um vetor, coerções estranhas acontecem: +c(TRUE, 4) # 1 4 +c("cachorro", TRUE, 4) # "cachorro" "TRUE" "4" +as.numeric("Bilbo") +# [1] NA +# Warning message: +# NAs introduced by coercion + +# Observe também: esses são apenas os tipos de dados básicos +# Existem muitos outros tipos de dados, como datas, séries temporais, etc. + + + +################################################## +# Variáveis, laços, expressões condicionais +################################################## + +# Uma variável é como uma caixa na qual você armazena um valor para uso posterior. +# Chamamos isso de "atribuir" o valor à variável. +# Ter variáveis nos permite escrever laços, funções e instruções com condição + +# VARIÁVEIS +# Existem muitas maneiras de atribuir valores: +x = 5 # é possível fazer assim +y <- "1" # mas é preferível fazer assim +TRUE -> z # isso funciona, mas é estranho + +# LAÇOS +# Nós temos laços com for +for (i in 1:4) { + print(i) +} +# [1] 1 +# [1] 2 +# [1] 3 +# [1] 4 +# Nós temos laços com while +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +# 10...9...8...7...6...5... +# Tenha em mente que os laços for e while são executados lentamente em R +# Operações em vetores inteiros (por exemplo, uma linha inteira, uma coluna inteira) +# ou funções do tipo apply() (discutiremos mais tarde) são mais indicadas + +# IF/ELSE +# Novamente, bastante padrão +if (4 > 3) { + print("4 é maior que 3") +} else { + print("4 não é maior que 3") +} +# [1] "4 é maior que 3" + +# FUNÇÕES +# Definidas assim: +jiggle <- function(x) { + x = x + rnorm(1, sd=.1) # adicione um pouco de ruído (controlado) + return(x) +} +# Chamada como qualquer outra função R: +jiggle(5) # 5±ε. Após set.seed(2716057), jiggle(5)==5.005043 + + + +########################################################################### +# Estruturas de dados: Vetores, matrizes, data frames e arranjos (arrays) +########################################################################### + +# UNIDIMENSIONAL + +# Vamos começar do início, e com algo que você já sabe: vetores. +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# Consultamos elementos específicos utilizando colchetes +# (Observe que R começa a contar a partir de 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +# Também podemos pesquisar os índices de componentes específicos, +which(vec %% 2 == 0) # 1 3 +# pegue apenas as primeiras ou últimas entradas no vetor, +head(vec, 1) # 8 +tail(vec, 2) # 10 11 +# ou descubra se um determinado valor está no vetor +any(vec == 10) # TRUE +# Se um índice for além do comprimento de um vetor, você obterá NA: +vec[6] # NA +# Você pode encontrar o comprimento do seu vetor com length() +length(vec) # 4 +# Você pode realizar operações em vetores inteiros ou subconjuntos de vetores +vec * 4 # 32 36 40 44 +vec[2:3] * 5 # 45 50 +any(vec[2:3] == 8) # FALSE +# e R tem muitas funções internas para sumarizar vetores +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 +# Mais alguns recursos embutidos: +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from=0, to=31337, by=1337) +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +# BIDIMENSIONAL (ELEMENTOS DA MESMA CLASSE) + +# Você pode fazer uma matriz com entradas do mesmo tipo assim: +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Ao contrário de um vetor, a classe de uma matriz é "matrix" independente do que ela contém +class(mat) # "matrix" +# Consulte a primeira linha +mat[1,] # 1 4 +# Execute uma operação na primeira coluna +3 * mat[,1] # 3 6 9 +# Consulte uma célula específica +mat[3,2] # 6 + +# Transponha toda a matriz +t(mat) +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# Multiplicação de matrizes +mat %*% t(mat) +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + +# cbind() une vetores em colunas para formar uma matriz +mat2 <- cbind(1:4, c("cachorro", "gato", "passaro", "cachorro")) +mat2 +# [,1] [,2] +# [1,] "1" "cachorro" +# [2,] "2" "gato" +# [3,] "3" "passaro" +# [4,] "4" "cachorro" +class(mat2) # matrix +# Mais uma vez, observe o que aconteceu! +# Como as matrizes devem conter todas as entradas da mesma classe, +# tudo foi convertido para a classe character +c(class(mat2[,1]), class(mat2[,2])) + +# rbind() une vetores linha a linha para fazer uma matriz +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# Ah, tudo da mesma classe. Sem coerções. Muito melhor. + +# BIDIMENSIONAL (CLASSES DIFERENTES) + +# Para colunas de tipos diferentes, use um data frame +# Esta estrutura de dados é tão útil para programação estatística, +# que uma versão dela foi adicionada ao Python através do pacote "pandas". + +estudantes <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), + c(3,2,2,1,0,-1), + c("H", "G", "G", "R", "S", "G")) +names(estudantes) <- c("nome", "ano", "casa") # nomeie as colunas +class(estudantes) # "data.frame" +estudantes +# nome ano casa +# 1 Cedric 3 H +# 2 Fred 2 G +# 3 George 2 G +# 4 Cho 1 R +# 5 Draco 0 S +# 6 Ginny -1 G +class(estudantes$ano) # "numeric" +class(estudantes[,3]) # "factor" +# encontre as dimensões +nrow(estudantes) # 6 +ncol(estudantes) # 3 +dim(estudantes) # 6 3 +# A função data.frame() converte vetores de caracteres em vetores de fator +# por padrão; desligue isso definindo stringsAsFactors = FALSE quando +# você criar um data frame +?data.frame + +# Existem muitas maneiras particulares de consultar partes de um data frame, +# todas sutilmente diferentes +estudantes$ano # 3 2 2 1 0 -1 +estudantes[,2] # 3 2 2 1 0 -1 +estudantes[,"ano"] # 3 2 2 1 0 -1 + +# Uma versão extendida da estrutura data.frame é a data.table +# Se você estiver trabalhando com dados enormes ou em painel, ou precisar mesclar +# alguns conjuntos de dados, data.table pode ser uma boa escolha. Aqui está um tour +# relâmpago: +install.packages("data.table") # baixe o pacote a partir do CRAN +require(data.table) # carregue ele +estudantes <- as.data.table(estudantes) +estudantes # observe a saída ligeiramente diferente +# nome ano casa +# 1: Cedric 3 H +# 2: Fred 2 G +# 3: George 2 G +# 4: Cho 1 R +# 5: Draco 0 S +# 6: Ginny -1 G +estudantes[nome=="Ginny"] # Consulte estudantes com o nome == "Ginny" +# nome ano casa +# 1: Ginny -1 G +estudantes[ano==2] # Consulte estudantes com o ano == 2 +# nome ano casa +# 1: Fred 2 G +# 2: George 2 G +# data.table facilita a fusão de dois conjuntos de dados +# vamos fazer outro data.table para mesclar com os alunos +fundadores <- data.table(casa=c("G","H","R","S"), + fundador=c("Godric","Helga","Rowena","Salazar")) +fundadores +# casa fundador +# 1: G Godric +# 2: H Helga +# 3: R Rowena +# 4: S Salazar +setkey(estudantes, casa) +setkey(fundadores, casa) +estudantes <- fundadores[estudantes] # mescle os dois conjuntos de dados com base na "casa" +setnames(estudantes, c("casa","nomeFundadorCasa","nomeEstudante","ano")) +estudantes[,order(c("nome","ano","casa","nomeFundadorCasa")), with=F] +# nomeEstudante ano casa nomeFundadorCasa +# 1: Fred 2 G Godric +# 2: George 2 G Godric +# 3: Ginny -1 G Godric +# 4: Cedric 3 H Helga +# 5: Cho 1 R Rowena +# 6: Draco 0 S Salazar + +# O data.table torna as tabelas de sumário fáceis +estudantes[,sum(ano),by=casa] +# casa V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + +# Para remover uma coluna de um data.frame ou data.table, +# atribua a ela o valor NULL +estudantes$nomeFundadorCasa <- NULL +estudantes +# nomeEstudante ano casa +# 1: Fred 2 G +# 2: George 2 G +# 3: Ginny -1 G +# 4: Cedric 3 H +# 5: Cho 1 R +# 6: Draco 0 S + +# Remova uma linha consultando parte dos dados +# Usando data.table: +estudantes[nomeEstudante != "Draco"] +# casa estudanteNome ano +# 1: G Fred 2 +# 2: G George 2 +# 3: G Ginny -1 +# 4: H Cedric 3 +# 5: R Cho 1 +# Usando data.frame: +estudantes <- as.data.frame(estudantes) +estudantes[estudantes$casa != "G",] +# casa nomeFundadorCasa nomeEstudante ano +# 4 H Helga Cedric 3 +# 5 R Rowena Cho 1 +# 6 S Salazar Draco 0 + +# MULTIDIMENSIONAL (TODOS OS ELEMENTOS DE UM TIPO) + +# Arranjos (arrays) criam tabelas n-dimensionais +# Todos os elementos devem ser do mesmo tipo +# Você pode fazer uma tabela bidimensional (como uma matriz) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +# Você pode usar array para fazer matrizes tridimensionais também +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + +# LISTAS (MULTIDIMENSIONAIS, POSSIVELMENTE IMPERFEITAS, DE DIFERENTES TIPOS) + +# Finalmente, R tem listas (de vetores) +lista1 <- list(tempo = 1:40) +lista1$preco = c(rnorm(40,.5*lista1$tempo,4)) # aleatória +lista1 +# Você pode obter itens na lista assim +lista1$tempo # um modo +lista1[["tempo"]] # um outro modo +lista1[[1]] # e ainda um outro modo +# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 +# [34] 34 35 36 37 38 39 40 +# Você pode obter itens de uma lista como qualquer outro vetor +lista1$preco[4] + +# Listas não são a estrutura de dados mais eficiente para se trabalhar em R; +# a menos que você tenha um bom motivo, você deve se ater a data.frames +# As listas geralmente são retornadas por funções que realizam regressões lineares + +################################################## +# A família de funções apply() +################################################## + +# Lembra de mat? +mat +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Use apply(X, MARGIN, FUN) para aplicar a função FUN a uma matriz X +# sobre linhas (MARGIN = 1) ou colunas (MARGIN = 2) +# Ou seja, R faz FUN para cada linha (ou coluna) de X, muito mais rápido que um +# laço for ou while faria +apply(mat, MAR = 2, jiggle) +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# Outras funções: ?lappy, ?sapply + +# Não as deixe te intimidar; todos concordam que essas funções são bem confusas + +# O pacote plyr visa substituir (e melhorar!) a família *apply(). +install.packages("plyr") +require(plyr) +?plyr + + + +######################### +# Carregando dados +######################### + +# "pets.csv" é um arquivo hospedado na internet +# (mas também poderia tranquilamente ser um arquivo no seu computador) +require(RCurl) +pets <- read.csv(textConnection(getURL("https://learnxinyminutes.com/docs/pets.csv"))) +pets +head(pets, 2) # primeiras duas linhas +tail(pets, 1) # última linha + +# Para salvar um data frame ou matriz como um arquivo .csv: +write.csv(pets, "pets2.csv") # para criar um novo arquivo .csv +# Define o diretório de trabalho com setwd(), confirme em qual você está com getwd() + +# Experimente ?read.csv e ?write.csv para obter mais informações + + + +######################### +# Análise estatística +######################### + +# Regressão linear! +modeloLinear <- lm(preco ~ tempo, data = lista1) +modeloLinear # imprime na tela o resultado da regressão +# Call: +# lm(formula = preco ~ tempo, data = lista1) +# +# Coefficients: +# (Intercept) tempo +# 0.1453 0.4943 +summary(modeloLinear) # saída mais detalhada da regressão +# Call: +# lm(formula = preco ~ tempo, data = lista1) +# +# Residuals: +# Min 1Q Median 3Q Max +# -8.3134 -3.0131 -0.3606 2.8016 10.3992 +# +# Coefficients: +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.14527 1.50084 0.097 0.923 +# tempo 0.49435 0.06379 7.749 2.44e-09 *** +# --- +# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 +# +# Residual standard error: 4.657 on 38 degrees of freedom +# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022 +# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09 +coef(modeloLinear) # extrai os parâmetros estimados +# (Intercept) tempo +# 0.1452662 0.4943490 +summary(modeloLinear)$coefficients # um outro meio de extrair os resultados +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 +# tempo 0.4943490 0.06379348 7.74920901 2.440008e-09 +summary(modeloLinear)$coefficients[,4] # the p-values +# (Intercept) tempo +# 9.234021e-01 2.440008e-09 + +# MODELOS LINEARES GERAIS +# Regressão logística +set.seed(1) +lista1$sucesso = rbinom(length(lista1$tempo), 1, .5) # binário aleatório +modeloLg <- glm(sucesso ~ tempo, data = lista1, + family=binomial(link="logit")) +modeloLg # imprime na tela o resultado da regressão logística +# Call: glm(formula = sucesso ~ tempo, +# family = binomial(link = "logit"), data = lista1) +# +# Coefficients: +# (Intercept) tempo +# 0.17018 -0.01321 +# +# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual +# Null Deviance: 55.35 +# Residual Deviance: 55.12 AIC: 59.12 +summary(modeloLg) # saída mais detalhada da regressão +# Call: +# glm(formula = sucesso ~ tempo, +# family = binomial(link = "logit"), data = lista1) + +# Deviance Residuals: +# Min 1Q Median 3Q Max +# -1.245 -1.118 -1.035 1.202 1.327 +# +# Coefficients: +# Estimate Std. Error z value Pr(>|z|) +# (Intercept) 0.17018 0.64621 0.263 0.792 +# tempo -0.01321 0.02757 -0.479 0.632 +# +# (Dispersion parameter for binomial family taken to be 1) +# +# Null deviance: 55.352 on 39 degrees of freedom +# Residual deviance: 55.121 on 38 degrees of freedom +# AIC: 59.121 +# +# Number of Fisher Scoring iterations: 3 + + +######################### +# Gráficos +######################### + +# FUNÇÕES DE PLOTAGEM INTEGRADAS +# Gráficos de dispersão! +plot(lista1$tempo, lista1$preco, main = "dados falsos") +# Trace a linha de regressão em um gráfico existente! +abline(modeloLinear, col = "red") +# Obtenha uma variedade de diagnósticos legais +plot(modeloLinear) +# Histogramas! +hist(rpois(n = 10000, lambda = 5), col = "thistle") +# Gráficos de barras! +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + +# GGPLOT2 +# Mas estes não são nem os mais bonitos dos gráficos no R +# Experimente o pacote ggplot2 para gráficos diferentes e mais bonitos +install.packages("ggplot2") +require(ggplot2) +?ggplot2 +pp <- ggplot(estudantes, aes(x=casa)) +pp + geom_bar() +ll <- as.data.table(lista1) +pp <- ggplot(ll, aes(x=tempo,preco)) +pp + geom_point() +# ggplot2 tem uma excelente documentação (disponível em http://docs.ggplot2.org/current/) + + + +``` + +## Como faço para obter R? + +* Obtenha o R e uma interface gráfica para o R em [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) é uma outra interface gráfica diff --git a/pt-br/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown index 3dd4a8d5..1080baa4 100644 --- a/pt-br/rust-pt.html.markdown +++ b/pt-br/rust-pt.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust filename: rust-pt.rs contributors: - ["Paulo Henrique Rodrigues Pinheiro", "https://about.me/paulohrpinheiro"] diff --git a/r.html.markdown b/r.html.markdown index e90d5a97..2746d1eb 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -4,6 +4,7 @@ contributors: - ["e99n09", "http://github.com/e99n09"] - ["isomorphismes", "http://twitter.com/isomorphisms"] - ["kalinn", "http://github.com/kalinn"] + - ["mribeirodantas", "http://github.com/mribeirodantas"] filename: learnr.r --- @@ -29,13 +30,13 @@ R is a statistical computing language. It has lots of libraries for uploading an # R without understanding anything about programming. Do not worry # about understanding everything the code does. Just enjoy! -data() # browse pre-loaded data sets -data(rivers) # get this one: "Lengths of Major North American Rivers" -ls() # notice that "rivers" now appears in the workspace -head(rivers) # peek at the data set +data() # browse pre-loaded data sets +data(rivers) # get this one: "Lengths of Major North American Rivers" +ls() # notice that "rivers" now appears in the workspace +head(rivers) # peek at the data set # 735 320 325 392 524 450 -length(rivers) # how many rivers were measured? +length(rivers) # how many rivers were measured? # 141 summary(rivers) # what are some summary statistics? # Min. 1st Qu. Median Mean 3rd Qu. Max. @@ -91,14 +92,15 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # 82 | 2 # make a histogram: -hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters -hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later +hist(rivers, col = "#333333", border = "white", breaks = 25) +hist(log(rivers), col = "#333333", border = "white", breaks = 25) +# play around with these parameters, you'll do more plotting later # Here's another neat data set that comes pre-loaded. R has tons of these. data(discoveries) -plot(discoveries, col="#333333", lwd=3, xlab="Year", +plot(discoveries, col = "#333333", lwd = 3, xlab = "Year", main="Number of important discoveries per year") -plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", +plot(discoveries, col = "#333333", lwd = 3, type = "h", xlab = "Year", main="Number of important discoveries per year") # Rather than leaving the default ordering (by year), @@ -109,7 +111,7 @@ sort(discoveries) # [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 # [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 -stem(discoveries, scale=2) +stem(discoveries, scale = 2) # # The decimal point is at the | # @@ -134,7 +136,7 @@ summary(discoveries) # 0.0 2.0 3.0 3.1 4.0 12.0 # Roll a die a few times -round(runif(7, min=.5, max=6.5)) +round(runif(7, min = .5, max = 6.5)) # 1 4 6 1 4 6 4 # Your numbers will differ from mine unless we set the same random.seed(31337) @@ -157,69 +159,68 @@ rnorm(9) # INTEGERS # Long-storage integers are written with L -5L # 5 -class(5L) # "integer" +5L # 5 +class(5L) # "integer" # (Try ?class for more information on the class() function.) # In R, every single value, like 5L, is considered a vector of length 1 -length(5L) # 1 +length(5L) # 1 # You can have an integer vector with length > 1 too: -c(4L, 5L, 8L, 3L) # 4 5 8 3 -length(c(4L, 5L, 8L, 3L)) # 4 -class(c(4L, 5L, 8L, 3L)) # "integer" +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" # NUMERICS # A "numeric" is a double-precision floating-point number -5 # 5 -class(5) # "numeric" +5 # 5 +class(5) # "numeric" # Again, everything in R is a vector; # you can make a numeric vector with more than one element -c(3,3,3,2,2,1) # 3 3 3 2 2 1 +c(3, 3, 3, 2, 2, 1) # 3 3 3 2 2 1 # You can use scientific notation too -5e4 # 50000 -6.02e23 # Avogadro's number -1.6e-35 # Planck length +5e4 # 50000 +6.02e23 # Avogadro's number +1.6e-35 # Planck length # You can also have infinitely large or small numbers -class(Inf) # "numeric" -class(-Inf) # "numeric" +class(Inf) # "numeric" +class(-Inf) # "numeric" # You might use "Inf", for example, in integrate(dnorm, 3, Inf); # this obviates Z-score tables. # BASIC ARITHMETIC # You can do arithmetic with numbers # Doing arithmetic on a mix of integers and numerics gives you another numeric -10L + 66L # 76 # integer plus integer gives integer -53.2 - 4 # 49.2 # numeric minus numeric gives numeric -2.0 * 2L # 4 # numeric times integer gives numeric -3L / 4 # 0.75 # integer over numeric gives numeric -3 %% 2 # 1 # the remainder of two numerics is another numeric +10L + 66L # 76 # integer plus integer gives integer +53.2 - 4 # 49.2 # numeric minus numeric gives numeric +2.0 * 2L # 4 # numeric times integer gives numeric +3L / 4 # 0.75 # integer over numeric gives numeric +3 %% 2 # 1 # the remainder of two numerics is another numeric # Illegal arithmetic yields you a "not-a-number": -0 / 0 # NaN -class(NaN) # "numeric" +0 / 0 # NaN +class(NaN) # "numeric" # You can do arithmetic on two vectors with length greater than 1, # so long as the larger vector's length is an integer multiple of the smaller -c(1,2,3) + c(1,2,3) # 2 4 6 +c(1, 2, 3) + c(1, 2, 3) # 2 4 6 # Since a single number is a vector of length one, scalars are applied # elementwise to vectors -(4 * c(1,2,3) - 2) / 2 # 1 3 5 +(4 * c(1, 2, 3) - 2) / 2 # 1 3 5 # Except for scalars, use caution when performing arithmetic on vectors with # different lengths. Although it can be done, -c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 -# Matching lengths is better practice and easier to read -c(1,2,3,1,2,3) * c(1,2,1,2,1,2) +c(1, 2, 3, 1, 2, 3) * c(1, 2) # 1 4 3 2 2 6 +# Matching lengths is better practice and easier to read most times +c(1, 2, 3, 1, 2, 3) * c(1, 2, 1, 2, 1, 2) # 1 4 3 2 2 6 # CHARACTERS # There's no difference between strings and characters in R -"Horatio" # "Horatio" -class("Horatio") # "character" -class('H') # "character" +"Horatio" # "Horatio" +class("Horatio") # "character" +class("H") # "character" # Those were both character vectors of length 1 # Here is a longer one: -c('alef', 'bet', 'gimmel', 'dalet', 'he') -# => -# "alef" "bet" "gimmel" "dalet" "he" +c("alef", "bet", "gimmel", "dalet", "he") +# => "alef" "bet" "gimmel" "dalet" "he" length(c("Call","me","Ishmael")) # 3 # You can do regex operations on character vectors: -substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." # R has several built-in character vectors: letters @@ -230,32 +231,33 @@ month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "D # LOGICALS # In R, a "logical" is a boolean -class(TRUE) # "logical" -class(FALSE) # "logical" + +class(TRUE) # "logical" +class(FALSE) # "logical" # Their behavior is normal -TRUE == TRUE # TRUE -TRUE == FALSE # FALSE -FALSE != FALSE # FALSE -FALSE != TRUE # TRUE +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE # Missing data (NA) is logical, too -class(NA) # "logical" +class(NA) # "logical" # Use | and & for logic operations. # OR -TRUE | FALSE # TRUE +TRUE | FALSE # TRUE # AND -TRUE & FALSE # FALSE +TRUE & FALSE # FALSE # Applying | and & to vectors returns elementwise logic operations -c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE -c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE +c(TRUE, FALSE, FALSE) | c(FALSE, TRUE, FALSE) # TRUE TRUE FALSE +c(TRUE, FALSE, TRUE) & c(FALSE, TRUE, TRUE) # FALSE FALSE TRUE # You can test if x is TRUE -isTRUE(TRUE) # TRUE +isTRUE(TRUE) # TRUE # Here we get a logical vector with many elements: -c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE -c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE +c("Z", "o", "r", "r", "o") == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c("Z", "o", "r", "r", "o") == "Z" # TRUE FALSE FALSE FALSE FALSE # FACTORS # The factor class is for categorical data -# Factors can be ordered (like childrens' grade levels) or unordered (like colors) +# Factors can be ordered (like grade levels) or unordered (like colors) factor(c("blue", "blue", "green", NA, "blue")) # blue blue green <NA> blue # Levels: blue green @@ -263,31 +265,27 @@ factor(c("blue", "blue", "green", NA, "blue")) # Note that missing data does not enter the levels levels(factor(c("green", "green", "blue", NA, "blue"))) # "blue" "green" # If a factor vector has length 1, its levels will have length 1, too -length(factor("green")) # 1 +length(factor("green")) # 1 length(levels(factor("green"))) # 1 # Factors are commonly seen in data frames, a data structure we will cover later -data(infert) # "Infertility after Spontaneous and Induced Abortion" +data(infert) # "Infertility after Spontaneous and Induced Abortion" levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" # NULL # "NULL" is a weird one; use it to "blank out" a vector -class(NULL) # NULL +class(NULL) # NULL parakeet = c("beak", "feathers", "wings", "eyes") -parakeet -# => -# [1] "beak" "feathers" "wings" "eyes" +parakeet # "beak" "feathers" "wings" "eyes" parakeet <- NULL -parakeet -# => -# NULL +parakeet # NULL # TYPE COERCION # Type-coercion is when you force a value to take on a different type -as.character(c(6, 8)) # "6" "8" -as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE # If you put elements of different types into a vector, weird coercions happen: -c(TRUE, 4) # 1 4 -c("dog", TRUE, 4) # "dog" "TRUE" "4" +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" as.numeric("Bilbo") # => # [1] NA @@ -309,14 +307,15 @@ as.numeric("Bilbo") # VARIABLES # Lots of way to assign stuff: -x = 5 # this is possible -y <- "1" # this is preferred -TRUE -> z # this works but is weird +x = 5 # this is possible +y <- "1" # this is preferred traditionally +TRUE -> z # this works but is weird +# Refer to the Internet for the behaviors and preferences about them. # LOOPS # We've got for loops for (i in 1:4) { - print(i) + print(i) } # We've got while loops a <- 10 @@ -341,11 +340,11 @@ if (4 > 3) { # FUNCTIONS # Defined like so: jiggle <- function(x) { - x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise + x = x + rnorm(1, sd=.1) # add in a bit of (controlled) noise return(x) } # Called like any other R function: -jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 +jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 @@ -357,39 +356,39 @@ jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 # Let's start from the very beginning, and with something you already know: vectors. vec <- c(8, 9, 10, 11) -vec # 8 9 10 11 +vec # 8 9 10 11 # We ask for specific elements by subsetting with square brackets # (Note that R starts counting from 1) -vec[1] # 8 -letters[18] # "r" -LETTERS[13] # "M" -month.name[9] # "September" -c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 # We can also search for the indices of specific components, -which(vec %% 2 == 0) # 1 3 +which(vec %% 2 == 0) # 1 3 # grab just the first or last few entries in the vector, -head(vec, 1) # 8 -tail(vec, 2) # 10 11 +head(vec, 1) # 8 +tail(vec, 2) # 10 11 # or figure out if a certain value is in the vector -any(vec == 10) # TRUE +any(vec == 10) # TRUE # If an index "goes over" you'll get NA: -vec[6] # NA +vec[6] # NA # You can find the length of your vector with length() -length(vec) # 4 +length(vec) # 4 # You can perform operations on entire vectors or subsets of vectors -vec * 4 # 32 36 40 44 -vec[2:3] * 5 # 45 50 -any(vec[2:3] == 8) # FALSE +vec * 4 # 32 36 40 44 +vec[2:3] * 5 # 45 50 +any(vec[2:3] == 8) # FALSE # and R has many built-in functions to summarize vectors -mean(vec) # 9.5 -var(vec) # 1.666667 -sd(vec) # 1.290994 -max(vec) # 11 -min(vec) # 8 -sum(vec) # 38 +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 # Some more nice built-ins: -5:15 # 5 6 7 8 9 10 11 12 13 14 15 -seq(from=0, to=31337, by=1337) +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from = 0, to = 31337, by = 1337) # => # [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 # [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 @@ -397,7 +396,7 @@ seq(from=0, to=31337, by=1337) # TWO-DIMENSIONAL (ALL ONE CLASS) # You can make a matrix out of entries all of the same type like so: -mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat <- matrix(nrow = 3, ncol = 2, c(1, 2, 3, 4, 5, 6)) mat # => # [,1] [,2] @@ -405,13 +404,13 @@ mat # [2,] 2 5 # [3,] 3 6 # Unlike a vector, the class of a matrix is "matrix", no matter what's in it -class(mat) # => "matrix" +class(mat) # "matrix" "array" # Ask for the first row -mat[1,] # 1 4 +mat[1, ] # 1 4 # Perform operation on the first column -3 * mat[,1] # 3 6 9 +3 * mat[, 1] # 3 6 9 # Ask for a specific cell -mat[3,2] # 6 +mat[3, 2] # 6 # Transpose the whole matrix t(mat) @@ -437,14 +436,14 @@ mat2 # [2,] "2" "cat" # [3,] "3" "bird" # [4,] "4" "dog" -class(mat2) # matrix +class(mat2) # matrix # Again, note what happened! # Because matrices must contain entries all of the same class, # everything got converted to the character class -c(class(mat2[,1]), class(mat2[,2])) +c(class(mat2[, 1]), class(mat2[, 2])) # rbind() sticks vectors together row-wise to make a matrix -mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 <- rbind(c(1, 2, 4, 5), c(6, 7, 0, 4)) mat3 # => # [,1] [,2] [,3] [,4] @@ -458,11 +457,11 @@ mat3 # This data structure is so useful for statistical programming, # a version of it was added to Python in the package "pandas". -students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), - c(3,2,2,1,0,-1), - c("H", "G", "G", "R", "S", "G")) +students <- data.frame(c("Cedric", "Fred", "George", "Cho", "Draco", "Ginny"), + c( 3, 2, 2, 1, 0, -1), + c( "H", "G", "G", "R", "S", "G")) names(students) <- c("name", "year", "house") # name the columns -class(students) # "data.frame" +class(students) # "data.frame" students # => # name year house @@ -472,21 +471,22 @@ students # 4 Cho 1 R # 5 Draco 0 S # 6 Ginny -1 G -class(students$year) # "numeric" -class(students[,3]) # "factor" +class(students$year) # "numeric" +class(students[,3]) # "factor" # find the dimensions -nrow(students) # 6 -ncol(students) # 3 -dim(students) # 6 3 -# The data.frame() function converts character vectors to factor vectors -# by default; turn this off by setting stringsAsFactors = FALSE when -# you create the data.frame +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 +# The data.frame() function used to convert character vectors to factor +# vectors by default; This has changed in R 4.0.0. If your R version is +# older, turn this off by setting stringsAsFactors = FALSE when you +# create the data.frame ?data.frame # There are many twisty ways to subset data frames, all subtly unalike -students$year # 3 2 2 1 0 -1 -students[,2] # 3 2 2 1 0 -1 -students[,"year"] # 3 2 2 1 0 -1 +students$year # 3 2 2 1 0 -1 +students[, 2] # 3 2 2 1 0 -1 +students[, "year"] # 3 2 2 1 0 -1 # An augmented version of the data.frame structure is the data.table # If you're working with huge or panel data, or need to merge a few data @@ -503,19 +503,19 @@ students # note the slightly different print-out # 4: Cho 1 R # 5: Draco 0 S # 6: Ginny -1 G -students[name=="Ginny"] # get rows with name == "Ginny" +students[name == "Ginny"] # get rows with name == "Ginny" # => # name year house # 1: Ginny -1 G -students[year==2] # get rows with year == 2 +students[year == 2] # get rows with year == 2 # => # name year house # 1: Fred 2 G # 2: George 2 G # data.table makes merging two data sets easy # let's make another data.table to merge with students -founders <- data.table(house=c("G","H","R","S"), - founder=c("Godric","Helga","Rowena","Salazar")) +founders <- data.table(house = c("G" , "H" , "R" , "S"), + founder = c("Godric", "Helga", "Rowena", "Salazar")) founders # => # house founder @@ -526,8 +526,8 @@ founders setkey(students, house) setkey(founders, house) students <- founders[students] # merge the two data sets by matching "house" -setnames(students, c("house","houseFounderName","studentName","year")) -students[,order(c("name","year","house","houseFounderName")), with=F] +setnames(students, c("house", "houseFounderName", "studentName", "year")) +students[, order(c("name", "year", "house", "houseFounderName")), with = F] # => # studentName year house houseFounderName # 1: Fred 2 G Godric @@ -538,7 +538,7 @@ students[,order(c("name","year","house","houseFounderName")), with=F] # 6: Draco 0 S Salazar # data.table makes summary tables easy -students[,sum(year),by=house] +students[, sum(year), by = house] # => # house V1 # 1: G 3 @@ -571,7 +571,7 @@ students[studentName != "Draco"] # 5: R Cho 1 # Using data.frame: students <- as.data.frame(students) -students[students$house != "G",] +students[students$house != "G", ] # => # house houseFounderName studentName year # 4 H Helga Cedric 3 @@ -583,13 +583,13 @@ students[students$house != "G",] # Arrays creates n-dimensional tables # All elements must be of the same type # You can make a two-dimensional table (sort of like a matrix) -array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +array(c(c(1, 2, 4, 5), c(8, 9, 3, 6)), dim = c(2, 4)) # => # [,1] [,2] [,3] [,4] # [1,] 1 4 8 3 # [2,] 2 5 9 6 # You can use array to make three-dimensional matrices too -array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +array(c(c(c(2, 300, 4), c(8, 9, 0)), c(c(5, 60, 0), c(66, 7, 847))), dim = c(3, 2, 2)) # => # , , 1 # @@ -609,7 +609,7 @@ array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) # Finally, R has lists (of vectors) list1 <- list(time = 1:40) -list1$price = c(rnorm(40,.5*list1$time,4)) # random +list1$price = c(rnorm(40, .5*list1$time, 4)) # random list1 # You can get items in the list like so list1$time # one way @@ -682,7 +682,7 @@ write.csv(pets, "pets2.csv") # to make a new .csv file ######################### # Linear regression! -linearModel <- lm(price ~ time, data = list1) +linearModel <- lm(price ~ time, data = list1) linearModel # outputs result of regression # => # Call: @@ -719,7 +719,7 @@ summary(linearModel)$coefficients # another way to extract results # Estimate Std. Error t value Pr(>|t|) # (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 # time 0.4943490 0.06379348 7.74920901 2.440008e-09 -summary(linearModel)$coefficients[,4] # the p-values +summary(linearModel)$coefficients[, 4] # the p-values # => # (Intercept) time # 9.234021e-01 2.440008e-09 @@ -728,8 +728,7 @@ summary(linearModel)$coefficients[,4] # the p-values # Logistic regression set.seed(1) list1$success = rbinom(length(list1$time), 1, .5) # random binary -glModel <- glm(success ~ time, data = list1, - family=binomial(link="logit")) +glModel <- glm(success ~ time, data = list1, family=binomial(link="logit")) glModel # outputs result of logistic regression # => # Call: glm(formula = success ~ time, @@ -745,8 +744,10 @@ glModel # outputs result of logistic regression summary(glModel) # more verbose output from the regression # => # Call: -# glm(formula = success ~ time, -# family = binomial(link = "logit"), data = list1) +# glm( +# formula = success ~ time, +# family = binomial(link = "logit"), +# data = list1) # Deviance Residuals: # Min 1Q Median 3Q Max @@ -780,7 +781,7 @@ plot(linearModel) # Histograms! hist(rpois(n = 10000, lambda = 5), col = "thistle") # Barplots! -barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) +barplot(c(1, 4, 5, 1, 2), names.arg = c("red", "blue", "purple", "green", "yellow")) # GGPLOT2 # But these are not even the prettiest of R's plots @@ -788,10 +789,10 @@ barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) install.packages("ggplot2") require(ggplot2) ?ggplot2 -pp <- ggplot(students, aes(x=house)) +pp <- ggplot(students, aes(x = house)) pp + geom_bar() ll <- as.data.table(list1) -pp <- ggplot(ll, aes(x=time,price)) +pp <- ggplot(ll, aes(x = time, price)) pp + geom_point() # ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) diff --git a/ru-ru/rust-ru.html.markdown b/ru-ru/rust-ru.html.markdown index d46d301c..a568ac37 100644 --- a/ru-ru/rust-ru.html.markdown +++ b/ru-ru/rust-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust filename: learnrust-ru.rs contributors: diff --git a/uk-ua/rust-ua.html.markdown b/uk-ua/rust-ua.html.markdown index 422de371..4aad0cbb 100644 --- a/uk-ua/rust-ua.html.markdown +++ b/uk-ua/rust-ua.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: diff --git a/zh-cn/python-cn.html.markdown b/zh-cn/python-cn.html.markdown index 4469443f..a4e53c1b 100644 --- a/zh-cn/python-cn.html.markdown +++ b/zh-cn/python-cn.html.markdown @@ -6,8 +6,10 @@ contributors: - ["Andre Polykanine", "https://github.com/Oire"] translators: - ["Geoff Liu", "http://geoffliu.me"] + - ["Maple", "https://github.com/mapleincode"] filename: learnpython-cn.py lang: zh-cn + --- Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 @@ -19,7 +21,6 @@ Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 注意:这篇教程是基于 Python 3 写的。如果你想学旧版 Python 2,我们特别有[另一篇教程](http://learnxinyminutes.com/docs/pythonlegacy/)。 ```python - # 用井字符开头的是单行注释 """ 多行字符串用三个引号 @@ -35,50 +36,66 @@ Python 是由吉多·范罗苏姆(Guido Van Rossum)在 90 年代早期设计。 3 # => 3 # 算术没有什么出乎意料的 -1 + 1 # => 2 -8 - 1 # => 7 +1 + 1 # => 2 +8 - 1 # => 7 10 * 2 # => 20 # 但是除法例外,会自动转换成浮点数 35 / 5 # => 7.0 -5 / 3 # => 1.6666666666666667 +10.0 / 3 # => 3.3333333333333335 # 整数除法的结果都是向下取整 -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # 浮点数也可以 --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # 浮点数也可以 +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 # 浮点数的运算结果也是浮点数 3 * 2.0 # => 6.0 # 模除 7 % 3 # => 1 +# i % j 结果的正负符号会和 j 相同,而不是和 i 相同 +-7 % 3 # => 2 -# x的y次方 +# x 的 y 次方 2**4 # => 16 # 用括号决定优先级 +1 + 3 * 2 # => 7 (1 + 3) * 2 # => 8 -# 布尔值 -True -False +# 布尔值 (注意: 首字母大写) +True # => True +False # => False -# 用not取非 -not True # => False +# 用 not 取非 +not True # => False not False # => True -# 逻辑运算符,注意and和or都是小写 +# 逻辑运算符,注意 and 和 or 都是小写 True and False # => False False or True # => True -# 整数也可以当作布尔值 -0 and 2 # => 0 --5 or 0 # => -5 +# True 和 False 实质上就是数字 1 和0 +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# 数值与 True 和 False 之间的比较运算 0 == False # => True 2 == True # => False 1 == True # => True +-5 != False # => True + +# 使用布尔逻辑运算符对数字类型的值进行运算时,会把数值强制转换为布尔值进行运算 +# 但计算结果会返回它们的强制转换前的值 +# 注意不要把 bool(ints) 与位运算的 "按位与"、"按位或" (&, |) 混淆 +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 # 用==判断相等 1 == 1 # => True @@ -94,43 +111,66 @@ False or True # => True 2 <= 2 # => True 2 >= 2 # => True +# 判断一个值是否在范围里 +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False # 大小比较可以连起来! 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# 字符串用单引双引都可以 +# (is 对比 ==) is 判断两个变量是否引用同一个对象, +# 而 == 判断两个对象是否含有相同的值 +a = [1, 2, 3, 4] # 变量 a 是一个新的列表, [1, 2, 3, 4] +b = a # 变量 b 赋值了变量 a 的值 +b is a # => True, a 和 b 引用的是同一个对象 +b == a # => True, a 和 b 的对象的值相同 +b = [1, 2, 3, 4] # 变量 b 赋值了一个新的列表, [1, 2, 3, 4] +b is a # => False, a 和 b 引用的不是同一个对象 +b == a # => True, a 和 b 的对象的值相同 + + +# 创建字符串可以使用单引号(')或者双引号(") "这是个字符串" '这也是个字符串' -# 用加号连接字符串 +# 字符串可以使用加号连接成新的字符串 "Hello " + "world!" # => "Hello world!" +# 非变量形式的字符串甚至可以在没有加号的情况下连接 +"Hello " "world!" # => "Hello world!" # 字符串可以被当作字符列表 -"This is a string"[0] # => 'T' +"Hello world!"[0] # => 'H' -# 用.format来格式化字符串 -"{} can be {}".format("strings", "interpolated") +# 你可以获得字符串的长度 +len("This is a string") # => 16 +# 你可以使用 f-strings 格式化字符串(python3.6+) +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" +# 你可以在大括号内几乎加入任何 python 表达式,表达式的结果会以字符串的形式返回 +f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long." + +# 用 .format 来格式化字符串 +"{} can be {}".format("strings", "interpolated") # 可以重复参数以节省时间 "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") # => "Jack be nimble, Jack be quick, Jack jump over the candle stick" - # 如果不想数参数,可以用关键字 "{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" -# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法 +# 如果你的 Python3 程序也要在 Python2.5 以下环境运行,也可以用老式的格式化语法 "%s can be %s the %s way" % ("strings", "interpolated", "old") # None是一个对象 None # => None -# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。 +# 当与 None 进行比较时不要用 ==,要用 is。is 是用来比较两个变量是否指向同一个对象。 "etc" is None # => False None is None # => True -# None,0,空字符串,空列表,空字典,空元组都算是False -# 所有其他值都是True +# None,0,空字符串,空列表,空字典,空元组都算是 False +# 所有其他值都是 True bool(0) # => False bool("") # => False bool([]) # => False @@ -145,16 +185,26 @@ bool(()) # => False # print是内置的打印函数 print("I'm Python. Nice to meet you!") +# 默认情况下,print 函数会在输出结果后加入一个空行作为结尾 +# 可以使用附加参数改变输出结尾 +print("Hello, World", end="!") # => Hello, World! + +# 可以很简单的从终端获得输入数据 +input_string_var = input("Enter some data: ") # 返回字符串数值 + # 在给变量赋值前不用提前声明 -# 传统的变量命名是小写,用下划线分隔单词 +# 习惯上变量命名是小写,用下划线分隔单词 some_var = 5 some_var # => 5 # 访问未赋值的变量会抛出异常 # 参考流程控制一段来学习异常处理 -some_unknown_var # 抛出NameError +some_unknown_var # 抛出 NameError + +# "if" 可以用作表达式,它的作用等同于 C 语言的三元运算符 "?:" +"yay!" if 0 > 1 else "nay!" # => "nay!" -# 用列表(list)储存序列 +# 用列表 (list) 储存序列 li = [] # 创建列表时也可以同时赋给元素 other_li = [4, 5, 6] @@ -174,128 +224,177 @@ li[0] # => 1 # 取出最后一个元素 li[-1] # => 3 -# 越界存取会造成IndexError -li[4] # 抛出IndexError +# 越界存取会造成 IndexError +li[4] # 抛出 IndexError # 列表有切割语法 -li[1:3] # => [2, 4] +li[1:3] # => [2, 4] # 取尾 -li[2:] # => [4, 3] +li[2:] # => [4, 3] # 取头 -li[:3] # => [1, 2, 4] +li[:3] # => [1, 2, 4] # 隔一个取一个 -li[::2] # =>[1, 4] +li[::2] # =>[1, 4] # 倒排列表 li[::-1] # => [3, 4, 2, 1] # 可以用三个参数的任何组合来构建切割 # li[始:终:步伐] -# 用del删除任何一个元素 -del li[2] # li is now [1, 2, 3] +# 简单的实现了单层数组的深度复制 +li2 = li[:] # => li2 = [1, 2, 4, 3] ,但 (li2 is li) 会返回 False + +# 用 del 删除任何一个元素 +del li[2] # li 现在为 [1, 2, 3] + +# 删除第一个匹配的元素 +li.remove(2) # li 现在为 [1, 3] +li.remove(2) # 抛出错误 ValueError: 2 is not in the list + +# 在指定索引处插入一个新的元素 +li.insert(1, 2) # li is now [1, 2, 3] again + +# 获得列表第一个匹配的值的索引 +li.index(2) # => 1 +li.index(4) # 抛出一个 ValueError: 4 is not in the list # 列表可以相加 -# 注意:li和other_li的值都不变 +# 注意:li 和 other_li 的值都不变 li + other_li # => [1, 2, 3, 4, 5, 6] -# 用extend拼接列表 -li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6] +# 用 "extend()" 拼接列表 +li.extend(other_li) # li 现在是[1, 2, 3, 4, 5, 6] -# 用in测试列表是否包含值 +# 用 "in" 测试列表是否包含值 1 in li # => True -# 用len取列表长度 +# 用 "len()" 取列表长度 len(li) # => 6 -# 元组是不可改变的序列 +# 元组类似列表,但是不允许修改 tup = (1, 2, 3) tup[0] # => 1 -tup[0] = 3 # 抛出TypeError +tup[0] = 3 # 抛出 TypeError + +# 如果元素数量为 1 的元组必须在元素之后加一个逗号 +# 其他元素数量的元组,包括空元组,都不需要 +type((1)) # => <class 'int'> +type((1,)) # => <class 'tuple'> +type(()) # => <class 'tuple'> -# 列表允许的操作元组大都可以 +# 列表允许的操作元组大多都可以 len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True # 可以把元组合列表解包,赋值给变量 -a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3 +a, b, c = (1, 2, 3) # 现在 a 是 1,b 是 2,c 是 3 +# 也可以做扩展解包 +a, *b, c = (1, 2, 3, 4) # 现在 a 是 1, b 是 [2, 3], c 是 4 # 元组周围的括号是可以省略的 -d, e, f = 4, 5, 6 +d, e, f = 4, 5, 6 # 元组 4, 5, 6 通过解包被赋值给变量 d, e, f # 交换两个变量的值就这么简单 -e, d = d, e # 现在d是5,e是4 +e, d = d, e # 现在 d 是 5,e 是 4 -# 用字典表达映射关系 +# 字典用来存储 key 到 value 的映射关系 empty_dict = {} # 初始化的字典 filled_dict = {"one": 1, "two": 2, "three": 3} +# 字典的 key 必须为不可变类型。 这是为了确保 key 被转换为唯一的哈希值以用于快速查询 +# 不可变类型包括整数、浮点、字符串、元组 +invalid_dict = {[1,2,3]: "123"} # => 抛出 TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # 然而 value 可以是任何类型 + # 用[]取值 filled_dict["one"] # => 1 - # 用 keys 获得所有的键。 -# 因为 keys 返回一个可迭代对象,所以在这里把结果包在 list 里。我们下面会详细介绍可迭代。 -# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。 -list(filled_dict.keys()) # => ["three", "two", "one"] +# 因为 keys 返回一个可迭代对象,所以我们需要把它包在 "list()" 里才能转换为列表。 +# 我们下面会详细介绍可迭代。 +# 注意: 对于版本 < 3.7 的 python, 字典的 key 的排序是无序的。你的运行结果 +# 可能与下面的例子不符,但是在 3.7 版本,字典中的项会按照他们被插入到字典的顺序进行排序 +list(filled_dict.keys()) # => ["three", "two", "one"] Python 版本 <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] Python 版本 3.7+ +# 用 "values()" 获得所有的值。跟 keys 一样也是可迭代对象,要使用 "list()" 才能转换为列表。 +# 注意: 排序顺序和 keys 的情况相同。 -# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。 -list(filled_dict.values()) # => [3, 2, 1] +list(filled_dict.values()) # => [3, 2, 1] Python 版本 < 3.7 +list(filled_dict.values()) # => [1, 2, 3] Python 版本 3.7+ # 用in测试一个字典是否包含一个键 "one" in filled_dict # => True 1 in filled_dict # => False -# 访问不存在的键会导致KeyError +# 访问不存在的键会导致 KeyError filled_dict["four"] # KeyError -# 用get来避免KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None -# 当键不存在的时候get方法可以返回默认值 +# 用 "get()" 来避免KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# 当键不存在的时候 "get()" 方法可以返回默认值 filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 +filled_dict.get("four", 4) # => 4 -# setdefault方法只有当键不存在的时候插入新值 -filled_dict.setdefault("five", 5) # filled_dict["five"]设为5 -filled_dict.setdefault("five", 6) # filled_dict["five"]还是5 +# "setdefault()" 方法只有当键不存在的时候插入新值 +filled_dict.setdefault("five", 5) # filled_dict["five"] 设为5 +filled_dict.setdefault("five", 6) # filled_dict["five"] 还是5 # 字典赋值 filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -filled_dict["four"] = 4 # 另一种赋值方法 +filled_dict["four"] = 4 # 另一种赋值方法 -# 用del删除 -del filled_dict["one"] # 从filled_dict中把one删除 +# 用 del 删除项 +del filled_dict["one"] # 从 filled_dict 中把 one 删除 -# 用set表达集合 +# 用 set 表达集合 empty_set = set() # 初始化一个集合,语法跟字典相似。 -some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4} +some_set = {1, 1, 2, 2, 3, 4} # some_set现在是 {1, 2, 3, 4} + +# 类似字典的 keys,set 的元素也必须是不可变类型 +invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' +valid_set = {(1,), 1} # 可以把集合赋值于变量 filled_set = some_set # 为集合添加元素 -filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5} +filled_set.add(5) # filled_set 现在是 {1, 2, 3, 4, 5} +# set 没有重复的元素 +filled_set.add(5) # filled_set 依然是 {1, 2, 3, 4, 5} -# & 取交集 +# "&" 取交集 other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} -# | 取并集 +# "|" 取并集 filled_set | other_set # => {1, 2, 3, 4, 5, 6} -# - 取补集 +# "-" 取补集 {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +# "^" 取异或集(对称差) +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# 判断左边的集合是否是右边集合的超集 +{1, 2} >= {1, 2, 3} # => False + +# 判断左边的集合是否是右边集合的子集 +{1, 2} <= {1, 2, 3} # => True + # in 测试集合是否包含元素 2 in filled_set # => True 10 in filled_set # => False +# 单层集合的深度复制 +filled_set = some_set.copy() # filled_set 是 {1, 2, 3, 4, 5} +filled_set is some_set # => False #################################################### ## 3. 流程控制和迭代器 @@ -304,28 +403,30 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} # 先随便定义一个变量 some_var = 5 -# 这是个if语句。注意缩进在Python里是有意义的 -# 印出"some_var比10小" +# 这是个if语句。注意缩进在Python里是有意义的! +# 缩进要使用 4 个空格而不是 tabs。 +# 这段代码会打印 "some_var is smaller than 10" if some_var > 10: - print("some_var比10大") -elif some_var < 10: # elif句是可选的 - print("some_var比10小") -else: # else也是可选的 - print("some_var就是10") + print("some_var is totally bigger than 10.") +elif some_var < 10: # elif 语句是可选的 + print("some_var is smaller than 10.") +else: # else 也是可选的 + print("some_var is indeed 10.") """ -用for循环语句遍历列表 +用 for 循环语句遍历列表 打印: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: + # 你可以使用 format() 格式化字符串并插入值 print("{} is a mammal".format(animal)) """ -"range(number)"返回数字列表从0到给的数字 +"range(number)" 返回数字列表从 0 到 number 的数字 打印: 0 1 @@ -334,9 +435,41 @@ for animal in ["dog", "cat", "mouse"]: """ for i in range(4): print(i) + +""" +"range(lower, upper)" 会返回一个包含从 lower 到 upper 的数字迭代器 +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) """ -while循环直到条件不满足 +"range(lower, upper, step)" 会返回一个,从 lower 到 upper、并且间隔值为 step 的迭代器。 +如果 step 未传入则会使用默认值 1 +prints: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) + +""" +遍历列表,并且同时返回列表里的每一个元素的索引和数值。 +prints: + 0 dog + 1 cat + 2 mouse +""" +animals = ["dog", "cat", "mouse"] +for i, value in enumerate(animals): + print(i, value) + +""" +while 循环直到条件不满足 打印: 0 1 @@ -348,20 +481,51 @@ while x < 4: print(x) x += 1 # x = x + 1 的简写 -# 用try/except块处理异常状况 + +# 用 try/except 块处理异常状况 try: - # 用raise抛出异常 + # 用 raise 抛出异常 raise IndexError("This is an index error") except IndexError as e: - pass # pass是无操作,但是应该在这里处理错误 + pass # pass 是无操作,但是应该在这里处理错误 except (TypeError, NameError): - pass # 可以同时处理不同类的错误 -else: # else语句是可选的,必须在所有的except之后 + pass # 可以同时处理不同类的错误 +else: # else语句是可选的,必须在所有的except之后 print("All good!") # 只有当try运行完没有错误的时候这句才会运行 +finally: # 在任何情况下都会执行 + print("We can clean up resources here") + +# 你可以使用 with 语句来代替 try/finally 对操作进行结束的操作 +with open("myfile.txt") as f: + for line in f: + print(line) + +# 写入文件 +contents = {"aa": 12, "bb": 21} +with open("myfile1.txt", "w+") as file: + file.write(str(contents)) # 写入字符串到文件 + +with open("myfile2.txt", "w+") as file: + file.write(json.dumps(contents)) # 写入对象到文件 + +# Reading from a file +with open("myfile1.txt", "r+") as file: + contents = file.read() # 从文件读取字符串 +print(contents) +# print: {"aa": 12, "bb": 21} + +with open("myfile2.txt", "r+") as file: + contents = json.load(file) # 从文件读取 json 对象 +print(contents) +# print: {"aa": 12, "bb": 21} + +# Windows 环境调用 open() 读取文件的默认编码为 ANSI,如果需要读取 utf-8 编码的文件, +# 需要指定 encoding 参数: +# open("myfile3.txt", "r+", encoding = "utf-8") -# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列 -# 的对象。比如说上面range返回的对象就是可迭代的。 +# Python 提供一个叫做可迭代 (iterable) 的基本抽象。一个可迭代对象是可以被当作序列 +# 的对象。比如说上面 range 返回的对象就是可迭代的。 filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() @@ -378,19 +542,24 @@ our_iterable[1] # 抛出TypeError our_iterator = iter(our_iterable) # 迭代器是一个可以记住遍历的位置的对象 -# 用__next__可以取得下一个元素 -our_iterator.__next__() # => "one" +# 用 "next()" 获得下一个对象 +next(our_iterator) # => "one" -# 再一次调取__next__时会记得位置 -our_iterator.__next__() # => "two" -our_iterator.__next__() # => "three" +# 再一次调取 "next()" 时会记得位置 +next(our_iterator) # => "two" +next(our_iterator) # => "three" -# 当迭代器所有元素都取出后,会抛出StopIteration -our_iterator.__next__() # 抛出StopIteration +# 当迭代器所有元素都取出后,会抛出 StopIteration +next(our_iterator) # 抛出 StopIteration -# 可以用list一次取出迭代器所有的元素 -list(filled_dict.keys()) # => Returns ["one", "two", "three"] +# 我们可以通过遍历还访问所有的值,实际上,for 内部实现了迭代 +our_iterator = iter(our_iterable) +for i in our_iterator: + print(i) # 依次打印 one, two, three +# 可以用 list 一次取出迭代器或者可迭代对象所有的元素 +list(filled_dict.keys()) # => 返回 ["one", "two", "three"] +list(our_iterator) # => 返回 [] 因为迭代的位置被保存了 #################################################### @@ -400,10 +569,10 @@ list(filled_dict.keys()) # => Returns ["one", "two", "three"] # 用def定义新函数 def add(x, y): print("x is {} and y is {}".format(x, y)) - return x + y # 用return语句返回 + return x + y # 用 return 语句返回 # 调用函数 -add(5, 6) # => 印出"x is 5 and y is 6"并且返回11 +add(5, 6) # => 打印 "x is 5 and y is 6" 并且返回 11 # 也可以用关键字参数来调用函数 add(y=6, x=5) # 关键字参数可以用任何顺序 @@ -434,33 +603,43 @@ all_the_args(1, 2, a=3, b=4) prints: {"a": 3, "b": 4} """ -# 调用可变参数函数时可以做跟上面相反的,用*展开序列,用**展开字典。 +# 调用可变参数函数时可以做跟上面相反的,用 * 展开元组,用 ** 展开字典。 args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) # 相当于 all_the_args(1, 2, 3, 4) all_the_args(**kwargs) # 相当于 all_the_args(a=3, b=4) all_the_args(*args, **kwargs) # 相当于 all_the_args(1, 2, 3, 4, a=3, b=4) +# 使用返回多个数值(返回值为元组类型) +def swap(x, y): + return y, x # 用不带括号的元组的格式来返回多个数值 + # (注意: 括号不需要加,但是也可以加) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # 同上,括号不需要加,但是也可以加 + # 函数作用域 x = 5 def setX(num): - # 局部作用域的x和全局域的x是不同的 + # 局部作用域的 x 和全局域的 x 是不同的 x = num # => 43 print (x) # => 43 def setGlobalX(num): global x print (x) # => 5 - x = num # 现在全局域的x被赋值 + x = num # 现在全局域的 x 被赋值 print (x) # => 6 setX(43) setGlobalX(6) -# 函数在Python是一等公民 +# 函数在 Python 是一等公民 def create_adder(x): def adder(y): return x + y @@ -470,39 +649,90 @@ add_10 = create_adder(10) add_10(3) # => 13 # 也有匿名函数 -(lambda x: x > 2)(3) # => True +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 # 内置的高阶函数 -map(add_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] # 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。 [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# 你也可以用这种方式实现对集合和字典的构建 +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + #################################################### -## 5. 类 +## 5. 模块 #################################################### +# 导入模块 +import math +print(math.sqrt(16)) # => 4.0 + +# 你可以导入模块中具体的函数 +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# 你可以导入模块中的所有的函数 +# 警告: 此操作不推荐 +from math import * + +# 你可以对模块名进行简化 +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python 模块实质上是 Python 文件 +# 你可以自己编写自己的模块,然后导入 +# 模块的名称和文件名相同 + +# 你可以用 "dir()" 查看模块中定义的函数和字段 +import math +dir(math) + +# 当你的脚本文件所在的文件夹也包含了一个名为 math.py 的 Python 文件 +# 这个 math.p 文件会被代替引入,而不是引入 Python 內建模块中的 math +# 出现这个情况的原因是本地文件夹的引入优先级要比 Python 內建库引入优先级要高 + + +#################################################### +## 6. 类 +#################################################### -# 定义一个继承object的类 -class Human(object): +# 我们使用 "class" 语句来创建类 +class Human: - # 类属性,被所有此类的实例共用。 + # 一个类的字段。 这个字段共享给这个类的所有实例。 species = "H. sapiens" - # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属 - # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这 - # 种格式。 + # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属性 + # 或方法对 Python 有特殊意义,但是允许用户自行定义。 + # 方法(可能是对象或者属性) 类似: __init__, __str__,__repr__ etc + # 都是特殊的方法 + # 你自己取名时不应该用这种格式 def __init__(self, name): - # Assign the argument to the instance's name attribute + # 将参数赋值给实例的 name 字段 self.name = name - # 实例方法,第一个参数总是self,就是这个实例对象 + # 初始化属性 + self._age = 0 + + # 实例方法,第一个参数总是self,也就是这个实例对象 def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) + print("{name}: {message}".format(name=self.name, message=msg)) + + # 另一个实例方法 + def sing(self): + return 'yo... yo... microphone check... one two... one two...' - # 类方法,被所有此类的实例共用。第一个参数是这个类对象。 + # 类方法,被所有此类的实例共用。 + # 第一个参数是这个类对象。 @classmethod def get_species(cls): return cls.species @@ -512,53 +742,225 @@ class Human(object): def grunt(): return "*grunt*" + # property 有点类似 getter + # 它把方法 age() 转换为同名并且只读的属性 + # 通常情况下,可以不需要编写复杂的 getter 和 setter。 + @property + def age(self): + return self._age + + # 允许属性被修改 + @age.setter + def age(self, age): + self._age = age + + # 允许属性被删除 + @age.deleter + def age(self): + del self._age + +# 当 Python 解释器在读取源文件的时候,就会执行文件中所有的代码 +# 对 __name__ 的检查可以保证这块代码只会在执行这个模块是住程序情况下被运行(而不是在引用时运行) +if __name__ == '__main__': + # + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i 和 j 都是 Human 实例化后的对象,换一句话说,它们都是 Human 实例 + + # 运行类方法 (classmethod) + i.say(i.get_species()) # "Ian: H. sapiens" + # 修改共享的类属性 + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # 运行静态方法 (staticmethod) + print(Human.grunt()) # => "*grunt*" + + # 实例上也可以执行静态方法 + print(i.grunt()) # => "*grunt*" + + # 更新实例的属性 + i.age = 42 + # 访问实例的属性 + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # 删除实例的属性 + del i.age + # i.age # => 这会抛出一个错误: AttributeError + + +#################################################### +## 6.1 类的继承 +#################################################### + +# 继承机制允许子类可以继承父类上的方法和变量。 +# 我们可以把 Human 类作为一个基础类或者说叫做父类, +# 然后定义一个名为 Superhero 的子类来继承父类上的比如 "species"、 "name"、 "age" 的属性 +# 和比如 "sing" 、"grunt" 这样的方法,同时,也可以定义它自己独有的属性 + +# 基于 Python 文件模块化的特点,你可以把这个类放在独立的文件中,比如说,human.py。 + +# 要从别的文件导入函数,需要使用以下的语句 +# from "filename-without-extension" import "function-or-class" + +from human import Human + +# 指定父类作为类初始化的参数 +class Superhero(Human): + + # 如果子类需要继承所有父类的定义,并且不需要做任何的修改, + # 你可以直接使用 "pass" 关键字(并且不需要其他任何语句) + # 但是在这个例子中会被注释掉,以用来生成不一样的子类。 + # pass + + # 子类可以重写父类定义的字段 + species = 'Superhuman' + + # 子类会自动的继承父类的构造函数包括它的参数,但同时,子类也可以新增额外的参数或者定义, + # 甚至去覆盖父类的方法比如说构造函数。 + # 这个构造函数从父类 "Human" 上继承了 "name" 参数,同时又新增了 "superpower" 和 + # "movie" 参数: + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # 新增额外类的参数 + self.fictional = True + self.movie = movie + # 注意可变的默认值,因为默认值是共享的 + self.superpowers = superpowers + + # "super" 函数让你可以访问父类中被子类重写的方法 + # 在这个例子中,被重写的是 __init__ 方法 + # 这个语句是用来运行父类的构造函数: + super().__init__(name) + + # 重写父类中的 sing 方法 + def sing(self): + return 'Dun, dun, DUN!' + + # 新增一个额外的方法 + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # 检查实例类型 + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') -# 构造一个实例 -i = Human(name="Ian") -print(i.say("hi")) # 印出 "Ian: hi" + # 获取方法解析顺序 MRO,MRO 被用于 getattr() 和 super() + # 这个字段是动态的,并且可以被修改 + print(Superhero.__mro__) # => (<class '__main__.Superhero'>, + # => <class 'human.Human'>, <class 'object'>) -j = Human("Joel") -print(j.say("hello")) # 印出 "Joel: hello" + # 调用父类的方法并且使用子类的属性 + print(sup.get_species()) # => Superhuman -# 调用一个类方法 -i.get_species() # => "H. sapiens" + # 调用被重写的方法 + print(sup.sing()) # => Dun, dun, DUN! -# 改一个共用的类属性 -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" + # 调用 Human 的方法 + sup.say('Spoon') # => Tick: Spoon -# 调用静态方法 -Human.grunt() # => "*grunt*" + # 调用 Superhero 独有的方法 + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # 继承类的字段 + sup.age = 31 + print(sup.age) # => 31 + + # Superhero 独有的字段 + print('Am I Oscar eligible? ' + str(sup.movie)) #################################################### -## 6. 模块 +## 6.2 多重继承 #################################################### -# 用import导入模块 -import math -print(math.sqrt(16)) # => 4.0 +# 定义另一个类 +# bat.py +class Bat: -# 也可以从模块中导入个别值 -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 + species = 'Baty' -# 可以导入一个模块中所有值 -# 警告:不建议这么做 -from math import * + def __init__(self, can_fly=True): + self.fly = can_fly -# 如此缩写模块名字 -import math as m -math.sqrt(16) == m.sqrt(16) # => True + # 这个类同样有 say 的方法 + def say(self, msg): + msg = '... ... ...' + return msg -# Python模块其实就是普通的Python文件。你可以自己写,然后导入, -# 模块的名字就是文件的名字。 + # 新增一个独有的方法 + def sonar(self): + return '))) ... (((' -# 你可以这样列出一个模块里所有的值 -import math -dir(math) +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + +# 现在我们来定义一个类来同时继承 Superhero 和 Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# 定义 Batman 作为子类,来同时继承 SuperHero 和 Bat +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # 通常要继承属性,你必须调用 super: + # super(Batman, self).__init__(*args, **kwargs) + # 然而在这里我们处理的是多重继承,而 super() 只会返回 MRO 列表的下一个基础类。 + # 因此,我们需要显式调用初始类的 __init__ + # *args 和 **kwargs 传递参数时更加清晰整洁,而对于父类而言像是 “剥了一层洋葱” + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # 重写了 name 字段 + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # 获取方法解析顺序 MRO,MRO 被用于 getattr() 和 super() + # 这个字段是动态的,并且可以被修改 + print(Batman.__mro__) # => (<class '__main__.Batman'>, + # => <class 'superhero.Superhero'>, + # => <class 'human.Human'>, + # => <class 'bat.Bat'>, <class 'object'>) + + # 调用父类的方法并且使用子类的属性 + print(sup.get_species()) # => Superhuman + + # 调用被重写的类 + print(sup.sing()) # => nan nan nan nan nan batman! + + # 调用 Human 上的方法,(之所以是 Human 而不是 Bat),是因为继承顺序起了作用 + sup.say('I agree') # => Sad Affleck: I agree + + # 调用仅存在于第二个继承的父类的方法 + print(sup.sonar()) # => ))) ... ((( + + # 继承类的属性 + sup.age = 100 + print(sup.age) # => 100 + + # 从第二个类上继承字段,并且其默认值被重写 + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False #################################################### @@ -583,6 +985,10 @@ for i in double_numbers(range_): print(i) if i >= 30: break +# 你也可以把一个生成器推导直接转换为列表 +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] # 装饰器(decorators) @@ -612,18 +1018,27 @@ print(say()) # Can you buy me a beer? print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` -## 想继续学吗? -### 线上免费材料(英文) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) +## 想继续学吗? -* [The Official Docs](http://docs.python.org/3/) -* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +### 在线免费材料(英文) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com/) +* [The Official Docs](https://docs.python.org/3/) +* [Hitchhiker’s Guide to Python](https://docs.python-guide.org/en/latest/) +* [Python Course](https://www.python-course.eu/) +* [Free Interactive Python Course](http://www.kikodo.io/) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](https://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](https://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](https://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](https://nbviewer.jupyter.org/gist/anonymous/5924718) +* [Python Tutorial for Intermediates](https://pythonbasics.org/) +* [Build a Desktop App with Python](https://pythonpyqt.com/) ### 书籍(也是英文) diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown index b77c9c38..6bed1650 100644 --- a/zh-cn/rust-cn.html.markdown +++ b/zh-cn/rust-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: rust +language: Rust contributors: - ["P1start", "http://p1start.github.io/"] translators: |