
。
[I]The Central Dogma of Gene Expression [II]Second Generation Sequencing Principle of illumina 1.sample prepAll preparation methods add adapters to the ends of the DNA fragments.Through reduced cycle amplification,additional motifs are introduced.Such as the sequencing binding site,indices and regions complementary to the flow cell oligos. 2.cluster generationClustering is a process where each fragment molecule is isothermally amplified.The flow cell is a glass slide with lanes.Each lane is a channel coated with a lawn,composed of two types of oligos.Hybridization is enable by the first of the two types of oligos on the surface.This oligos is complementary to the adapter region on one of the fragment strands.A polymerase creates a complement of the hybridized fragment.The double stranded molecule is denatured and the original template is washed away.The strands are clonally amplified through bridge amplification.In this process the strand folds over and the adapter region hybridizes to the second type of oligo on the flow cell.Polymerases generate the complementary strand forming a double stranded bridge .This bridge is denatured resulting in 2 single-stranded copies of the molecule that are tethered to the flow cell.The process is then repeated over and over,and occurs simultaneously for millions of clusters resulting in clonal amplification of all the fragments.After bridge amplification the reverse strands are cleaved and washed off,leaving only the forward strands.The three prime ends are blocked to prevent unwanted priming.3.sequencingSequencing begins with the extension of the first sequencing primer to produce the first read.With each cycle,fluorescently tagged nucleotides compete for addition to the growing chain.Only one is incorporated based on the sequence of the template.After the addition of each nucleotide the clusters are excited by a light source and a characteristic fluorescent signal is emitted.Sequencing-by-Synthesis.The number of cycles determines the length of the read.The emission wave length,along with the signal intensity,determines the base call.For a given cluster,all identical strands are read simultaneously.Hundreds of millions of clusters are sequenced in a massively parallel process.After the completion of the first read.,the read product is washed away.In this step the index/read primer is introduced and hybridized to the template.The read is generated,similar to the first read.After completion of the index read,the read product is washed off,and the three prime ends of the template are deprotected .The template how folds over and binds the second oligo on the flow cell?Index 2 is read in the same manner as index1.Polymerases extend the second flow cell oligo forming a double stranded bridge.This double stranded DNAis then linearized and the three prime ends are blocked.The original forward strand is cleaved off and washed away leaving only the reverse strand.Read 2 begins with the introduction of the read 2 sequencing primer.As with read1,the sequencing steps are repeated until the desired read length is achieved.Thet read 2 product is then washed away.This entire process generates millions of reads representing all the fragments.4.data analysisSequences from pooled sample libraries are separated preparation.For each sample,reads with similar stretches of base calls are aligned back to the reference genome for variant identification.The paired and information is used to resolve ambiguous alignments.Genomic data can be securely transferred,stored,analyzed and shared in base base sequence hub.Discover the possibilities of next-generation sequencing. [III]Software comparison softwareBWA-MEN reads software htseq-count [IV]Normalize log2 p-value q-value TPM FPKM RPKW [V]Differential Gene [VI]Evaluation TP=True Positive:actual is positive;forecast is positive;TN=True Negative:actual is positive;forecast is negative;FP=False Positive:actual is negative;forecast is positive;FN=False Negative:actual is negative.forecast is negative; $$ accuracy=\frac{TP+TN}{TP+TN+FP+FN} $$ $$ error rate=\frac{FP+FN}{TP+TN+FP+FN}=1-accuracy $$ $$ sensitive=\frac{TP}{P} $$ $$ specificity=\frac{TN}{N} $$ $$ precision=\frac{TP}{TP+FP} $$ $$ recall=\frac{TP}{TP+FN}=\frac{TP}{P}=sensitive $$ $$ f-measure=\frac{({\alpha}^2+1)*p*r}{{\alpha}^2*(p+r)}(\alpha=1) $$ END!
[I]Regression OLSregression Description Function simple linear regression lm(Y~X1,data) polynomial regression lm(Y~X1+...+I(X^2),data) multiple linear regression lm(Y~X1+X2+...+Xk) multiple linear regression with interaction terms lm(Y~X1+X2+X1:X2) selection the optimal regression model Function Description anova(fit1,fit2) nested model fit AIC(fit1,fit2) statistical fit stepAIC(fit,direction=) stepwise method:"forward""backward" regsubsets() all-subsets regression test Function Description plot() plot qqplot() quantile comparison durbinWatsonTest() Durbin-Waston crPlots() component and residual ncvTest() score test of non-constant error variance spreadLevelPlot() dispersion level outlierTest() Bonferroni outlier avPlots() added variable inluencePlot() regression scatterplot() enhanced scatter plot scatterplotMatrix() enhanced scatter plot matrix vif() variance expansion factor abnormal abnormal observation 1.outlier:outlierTest()2.high leverage point:hat.plot()3.strong influence point:Cook's D improvement measures 1.delete observation point2.variable transformation3.addition and deletion of variables Generalized Linear generalized linear glm()Distribution Family | Default Connection Function binomial (link = "logit") gaussian (link = "identity") gamma (link = "inverse") inverse.gaussian (link = "1/mu^2") poisson (link = "log") quasi (link = "identity",variance = "constant") quasibinomial (link = "logit") quasipoisson (link = "log") function with glm()Function | Description summary() show details of the fitting model coefficients()/coef() list the parameters of the fitting model confint() give a confidence interval for the model paramenters residuals() list residual value of the fitting model anova() generate an analysis table of variance for two fitting model plot() generate a diagnostic map of the evaluation fitting model predict() forecast new datasets with a fitting model deviance() the deviation of the fitting model df.residual() the residual freedom of the fitting model logistic > data(Affairs,package="ARE") > summary(Affairs) > table(Affair$affairs) > Affairs$ynaffair[Affairs$affairs > 0] <-1 > Affairs$ynaffair[Affairs$affairs == 0] <-0 > Affairs$naffair <- factor(Affairs$ynaffair),levels=c(0,1),labels=c("No","Yes")) > table(Affairs$ynaffair) > fit.full <-glm(ynaffair~gender + age + yearmarried +children + religiousness + education + occupation + rating,family = binomial() data = Affairs) > fit.reduced <-glm(ynaffair ~ age + yearmarried + religiousness +rating, family = binomial(),data = Affairs) > anova(fit.reduced,fit.full,test="Chisq") > coef(fit.reduced) > exp(coef(fit.reduced)) > testdata<-data.frame(rating=c(1,2,3,4,5),age=mean(Affair$age), yearsmarried=mean(Affairs$yearsmsrraied), religiousness=mean(Affairs$religiousness)) > teatdata > testdata$prob <- predict(fit.reduced,newdata=testdata,type="response") > testdata <- data.frame(rating = mean(Affair$rating), age=seq(17,57,10), yearsmarried=mean(Affair$yearsmarried), religiousness=mean(Affairs$religiousness)) > testdata > testdata$prob<-predict(fit.reduced,newdata=testdata,type="response") > testdata > deviance(fit.reduced)/df.residual(fit.reduced) > fit <- glm(ynaffair ~ age + yearmarried + religiousness + rating, family = quasibinomial(),data=Affairs) > pchisq(summary(fit.od)$dispersion * fit$df.residual, fit$df.residual,lower=F) poisson > data(breslow.dat,package="robust") > name(breslow.dat) > summary(breslow.dat[c(6,7,8,10)]) > opar<-par(no.readonly=TRUE) > par(mfrow=c(1,2)) > attach(breakslow.dat) > hist(sumY,breaks=20,xlab="Seizure Count",main="Distribution of Seizures") > boxplot(sumY~Trt,xlab="Treatment",main="Group Comparisons") > par(opar) > fit<-glm(sumY~Base + Age +Trt,data=breslow.dat,family=poisson()) > summary(fit) > coef(fit) > exp(coef(fit)) > deviance(fit)/df.residual(fit) > library(qcc) > qcc.overdispersion.test(breslow.dat$sumY,type="poisson") > fit.od<-glm(sumY~Base + Age + Trt,data=breslow.dat, family=quassipossion()) > summary(fit.od) > fit glm(sumY~Base + Age +Trt,data=breslow.dat,offset=log(time),family=poisson) [II]Cluster 1.cluster analysis step 1.choose the right variable2.scale data3.looking for anomalies4.calculated distance5.selection clustering algorithm6.obtain one or more clustering methods7.determine the number of classes8.get the ultimate clustering solution9.visualization of results10.interpretation class11.validation results 2.calculated distance > data(nurtrient,package="flexclust") > head(nutrient,4) > d<-dist(nutrient) > as.martrix(d)[1:4,1:4] 3.hierarchical clustering analysis > data(nutrient,package="flexclust") > row.name(nutrient) <-tolower(row.names(nutrient)) > nutrient.scaled<-scale(nutrient) > d<-dist(nutrient.scaled) > fit.average <-hclust(d,method="average") > plot(fit.average,hang=-1,cex=.8,main="Average Linkage Clustering") > library(Nbcluster) > devAskNewPage(ask=TRUE) > nc<-NbClust(nutrient,scaled,distance="euclidean", min.nc=2,max.nc=15,method="average") > table(nc$Best.n[1,]) > barplot(table(nc$Best,n[1,]), xlab="Number of Clusters",ylab="Number of Criteria", main="Number of Cluster Chosen by 26 Criteria") > clusters<-cutree(fit.average,k=5) > table(clusters) > aggregate(nutrient,by=list(cluster=clusters),median) > aggregate(as.data.frame(nutrient.scaled),bu=list(cluster=clusters),median) > plot(fit.average,hang=-1,cex=.8, main="Average Linkage Cluster\n5 Cluster Solution") > rect.hclust(fit.average,k=5) 4.Clustering analysis K-means clustering > wssplot<-function(data,nc=15,seed=1234)( > head(wine) > df<-scale(wine[-1]) > wssplot(df) > library(NcClust) > set.seed(1234) > devAskNewPage(ask=TRUE) > nc<-NbClust(df,min.nc=2,max.nc=15,method="kmeans") > table(nc$Best.n[1,) > barplot(table(nc$Best,n[1,]), xlab="Number of Clusters",ylab="Number of Criteria", main="Number of Clusters Chosen by 26 Criteria") > set.seed(1234) > fit.km<-kmeans(df,3,nstart=25) > fit.km$size > fit.km$centers > aggregate(wine[-1],by=list(cluster=fit.km$cluster),mean) Division around the center point > library(cluster) > set.seed(1234) > fit.pam<-pam(wine[-1],k=3,stand=TRUE) > fit.pam$medoids > clusplot(fit.pam,main="Bivariate Cluster Plot") > ct.pam<-table(wine$Type,fit.pam$clustering) > randIndex(ct.pam) 5.avoid non-existing classes > library(fMultivar) > set.seed(1234) > df<-rnom2d(1000,rho=.5) > df<-as.data.frame(df) > plot(df,main="Bivariate Normal Distribution with rho=0.5") > wssplot(df) > library(NbClust) > nc<-NbClust(df,min.nc=2,max.nc=15,method="kmean") > dev.new() > barplot(table(nc$Best,n[1,]), xlab="Number of Clusters",ylab="Number of Criteria", main="Number of Clusters Chosen by 26 Criteria") > library(ggplot2) > library(cluster) > fit<-pam(df,k=2) > df$clustering<-factor(fit$clustering) > ggplot(data=df,aes(x=V1,y=V2,color=clustering,shape=clustering)) + geom_point() + ggtitle("Clustering of Bivariate Normal Data") > plot(nc$All,index[,4],type="o",ylab="CCC",xlab="Number of clusters",col="blue") [III]Classification data preparation > loc<-"http://archive.ics.uci.edu/ml/machine-learning-databases/" > ds<-"breast-cancer-wisconsin/breast-cancer-wisconsin.data" > url<-paste(loc,ds,sep="") > breast<-read.table(url,sep=",",header=FALSE,na.string="?") > names(breast)<-c("ID","clumpThickness","sizeUniformity", "shapeUniformity","maginalAdhesion", "singleEpitheliaCellSize","bareNuclei", "blandChromatin","normalNucleoli","mitosis","class") > df<-breast[-1] > df$class<-factor(df$class,levels=c(2,4), labels=c("benign","malignant")) > set.seed(1234) > train<-sample(nrow(df),0.7*nrow(df)) > df.train<-df[train,] > df.validate<-df[-train,] > table(df.train$class) > table(df.validate$class) logistic regression > fit.logit<-glm(class~.,data=df.train,family=binomial()) > summary(fit.logit) > prob<-predict(fit.logit,df.validate,type="response") > logit.perd<-factor(prob>.5,levels=c(FALSE,TRUE), labels=c("benign","malignant")) > logit.perf<-table(df.validate$class,logit.pred, dnn=c("Actual","Predicted")) > logit.perf decision tree classic decision tree > library(repart) > set.seed(1234) > dtree<-repart(class~.,data=df.train,method="class", parms=list(split="information")) > dtree$cptable > plotcp(dtree) > dtree.pruned<-prune(dtree,cp=.0125) > library(repart.plot) > prp(dtree.pruned,type=2,extra=104, fallen.leaves=TRUE,main="Decesion Tree") > dtree.pred<-predict(dtree.pruned,df.validate,type="class") > dtree.perf<-table(df.validate$class,dtree.pred, dnn=c("Actual","Predicted")) > dtree.perf conditional inference tree > library(party) > fit.ctree<-ctree(class~.,data=sf.train) > plot(fit.ctree,main="Conditional Inference Tree") > ctree.pred<-predict(fit.ctree,df.validate,type="response") > ctree.perf<-table(df.validate$class,ctree.pred dnn=c("Actual","Predicted")) > stree.perf random forest > library(randomForest) > set.seed(1234) > fit.forest<-randomForest(class~.,data=df.train,na.action=na.roughfix,importance=TRUE) > fit.forest > importance(fit.forest,type=2) > forest.pred<-predict(fit.forest,df.validate) > forest.perf<-table(df.validate$class,forest.pred, dnn=c("Actual","Predicted")) > forest.perf support vector machines svm > library(e1071) > set.seed(1234) > fit.svm<-svm(class~.,data=df.train) > fit.svm > svm,pred<-predict(fit.svm,na.omit(df.validate)) > svm.perf<-table(na.omit(df.validate)$class, svm,pred,dnn=c("Actual","Predicted")) > svm.perf svm model with rbf core > set.seed(1234) > tuned<-tune.svm(class~.,data=df.train,gamma=10^(-6:1),cost=10^(-10:10)) > turned > fit.svm<-svm(class~.,data=df.train,gamma=.01,cost=1) > svm.pred<-predict(fit.svm,na.omit(df,validate)) > svm.perf<-table(na.omit(df.validate)$class, svm.pred,dnn=c("Actual","Predicted")) > svm.perf choose the best solution for forecasting > performance<-function(table,n=2){ if(!all(dim(table)==c(2,2))) stop("Must be a 2 × 2 table") tn=table[1,1] fp=table[1,2] fn=table[2,1] tp=table[2,2] sensitivity=tp/(tp+fn) specificity=tn/(tn+fp) ppp=tp/(tp+fp) npp=tn/(tn+fn) hitrate=(tp+tn)/(tp+tn+fp+fn) result<-paste("Sensitivity=",round(ppp,n), "\nSpecificity=",round(specificity,n), "\nPositive Predictive Value=",round(ppp,n), "\nNegative Predictive Value=",round(npp,n), "\nAccuracy=",round(hitrate,n),"\n",seq="") cat(result) } data mining with the rattle package > install.packages("rattle") > rattle() > loc<-"http://archive.ics.uci.edu/ml/machine-learning-databases/" > ds<-"pima-indians-diabetes/pima-indians-diabetes.data" > url <-paste(loc,ds,sep="") > diabetes<-read.table(url,seq=",",header=FALSE) > names(diabetes)<-c("npregant","plasma","bp","triceps", "insulin","bmi","pedigree","age","class") > diabetes$class<-factor(diabetes$class,levels=c(0,1), labels=c("normal","diabetic")) > library(rattle) > rattle() > cv<-matrix(c(145,50,8,27),nrow=2) > performance(as.table(cv)) [IV]Time Series Function Package Description ts() stats generate timing objects plot() graphics draw a line graph of the time series start() stats return the start time of the time series end() stats return the end time of the time series frequency() stats return the number of time points of the time series windows() stats subset a sequence object ma() forecast fit a simple moving average model stl() stats use LOESS smooth to decompose timing into seasonal terms,trend terms and random terms monthplot() stats draw seasonal terms in time series seasonplot() forecast generate seasonal plot HoltWinters() ststs fit exponential smoothing model forecast() forecast predicting the future value of the timing accuracy() forecast return time-of-fit goodness variable ets() forecast fit exponential smoothing model and automatically select the optimal model lag() stats return the timing after the specified hysteresis is taken Acf() forecast estimated autocorrelation function Pacf() forecast estimated partial autocorrelation function diff() base return the sequence after the lag term or difference ndiffs() forecast find the optimal difference count to remove the trend terms in the sequence adf.test() tseries perform an ADF test on the sequence to determine if it is stable arima stats fit the ARIMA model Box.test() ststs perform a Ljung-Box test to determine if the model's residuals are independent bds.test() teeries perform a BDS test to determine whether random variables in the sequence are subject to independent and identical distribution auto.arima forecast automatically select the ARIMA model END!
[I]Missing Value 1.identify missing value x is.na(x) is.nan(x) is.infinite(x) x<-NA TRUE FALSE FALSE x<-0/0 TRUE TRUE FALSE x<-1/0 FALSE FALSE TRUE is.na(x):missing value is.nan(x):impossible value is.infinite(x):infinite value complete.cases():missing values are NA and NaN;Inf and -Inf are valid values > mydata(data,package="") #loading > data[complete.cases(data),] #no missing value row > data[!complete.cases(data),] #one or more missing value row 2.missing pattern Pattern Package Function Description list mice md.pattern(x) 0:missing value;1:no missing value graphic VIM aggr(x,prop=FALSE,number=TRUE) number=FALSE(default):delete numberical label graphic VIM matrixplot(x,pch=,col=) light color:small value,dark color:great value,red:default missing value related none none x<-as.data.frame(abs(is.na(data)))head(x,5)y<-x[which(apply(x,2,sum)>0)]cor(data,y,use="pairwise.complete.obs") 3.processing missing value Method Description raw delete newdata<-na.omit(mydata) MI library(mice)imp<-mice(data,m)fit<-with(imp,analysis)pooled<-pool(fit)summary(pooled) mvnmle maximum likelihood estimation of missing values in multivariate normal distribution data cat multiple interpolation of multi-category variable in log-linear models arraryImputearraryMissPatternSeqknn microarrary missing data longitudinalData related function list kmi multiple interpolation Kaplan-Meier mix multiple interpolation mixed type data with continuous data pan multi-panel data or cluster data [II]Date Value Function Description date() output current date and time Sys.Date() output current date as.Date(x,"input_format") character convert to date as.character(dates) date covert to character difftime(date1,date2,units=) time interval,units="weeks"/"days"/"hours"/"minutes"/seconds" format(x,format="output_format") output date in the specified format input/output format Symbol Description Example %d 0~31 01 %a abbreviated week name Mon %A non-abbreviated week name Monday %m month 01 %b abbreviated month Jan %B non-abbreviated month January %y two-digit year 19 %Y four-digit year 2019 [III]Type Conversion Judgement Conversion is.numeric() as.numeric() is.character() as.character() is.vector() as.vector() is.matrix() as.matrix() is.date.frame() as.data.frame() is.factor() as.factor() is.logical() as.logical() [IV]Data Sorting > newdata<-dataframe[order(x1,x2),] #x_i=x,ascending;x_i=-x,descending [V]Data merging > total<-merge(dataframeA,dataframeB,by="x1") #column > total<-cbind(dataframeA,dataframeB) #direct column merger > total<-rbind(dataframeA,dataframeB) #direct row merger [VI]Subset of Dataset > newdata<-dataframe[row indices,column indices] #save variable > dataframe$x1<-dataframe$x2<-NULL #delete variable x1,x2 > newdata<subset(dataframe,condition) > mysample<-dataframe[sample(1:nrow(dataframe),extracting elements,replace=),] #replace=FALSE/TRUE(put/back) [VII]Processing Functions 1.math functions Function Description abs(x) absolute value sqrt(x) squart root ceiling(x) minimum integer not less than x floor(x) maximum integer not greater than x trunc(x) integer part from 0 to x round(x,digits=n) specified n is the decimal number of x signif(x,digits=n) specified n is the effective number of x cos(x),sin(x),tan(x) cosine,sine,tangent acos(x),asin(x),atan(x) arccosine,arcsine,arctangent cosh(x),sinh(x),tanh(x) hyperbolic cosine,hyperbolic sine,hyperbolic tangent acosh(x),asinh(x),atanh(x) inverse hyperbolic cosine,inverse hyperbolic sine,inverse hyperbolic tangent log(x,base=n) base=n,logarithm of x;log(x):base value=e;log10(x):base value=10 exp(x) exponential function 2.statistical function Function Description mean(x) mean madian(x) madian sd(x) standard deviation var(x) variance mad(x) median absolute deviation quantile(x,probs) quantile range(x) range sum(x) summary diff(x,lag=n) hysteresis difference min(x) minimum max(x) maximum scale(x,center=TRUE,scale=TRUE) centralization:center=TRUE;standardization:center=TRUE,scale=TRUE 3.probability function > [d/p/q/r]distribution_abbreviation() d=density p=distribution function q=quantile function r=random function Distribution Abbreviation Beta beta Binomial binom Cauchy caushy Chi-square chisq Exponential exp F f Gamma gamma Geometric geom Hypergeometric hyper Logarithm normal lnorm Logistic logis Multiple multinom Negative Binomial nbinom Normal norm Poission pois Wilcoxon signrank T t Uniform unif Weibull weibull Wilcoxon wilcox 4.character processing function Function Description nchar(x) character amount of x substr(x,start,stop) extract or replace a substring in a character vetor grep(pattern,x,ignore,case=FALSE,fixed=FALSE) search for a pattern in x.Regular Expression:fixed= FALSE;Text string:fixed=TRUE sub(pattern,replacement,x,ignore,case=FALSE,fixed=FALSE) search for a pattern in x and replacing by text replacement strsplit(x,split,fixed=FALSE) separate x in split paste(...,sep="") connection string with separator sep toupper(x) convert to uppercase tolower(x) convert to lowercase 5.others Function Description length(x) the length of x seq(from,to,by) generate a sequence rep(x,n) repeat x times n times cut(x,n) separate x into n parts pretty(x,n) create beautiful split points cat(...,file="mylife",append=FALSE) connection ... and output a file apply(x,MARGIN,FUN,...) x:data,MARGIN:subscript of dimension,FUN:specified function Homemade function > myfunction<-function(arg1,arg2,..){ statements return(object) } [VIII]Control Flow Description Function Repeat and Loop for(var in seq) statement while (cond) statement Conditional Execution if (cond) statement if (cond) statement1 else statement2 ifelse(cond,statement1,statement2) switch(expr,...) [IX]Aggregate and Reshape Function Description t(x) Transpose aggregate(x,by,FUN) x=data,by:a list of variable name,FUN:function melt(x,variance) reshape2 package,data melt dcast(md,formula,fun.aggregate) md:melted data,formula:variance1~variance i,fun.aggregate:aggregate function [X]component analysis step analysis diagram of principal component/exploratory factor principal component analysis 1.determine the number of principal > library(psych) > fa.parallel(Harman23.cor$cov,n.obs=302,fa="pc",n.iter=100, show.legend=FALSE,main="Scree plot with parallel analysis") 2.extracting the main component > pc<-principal(r=USJudgeRatings[,-1],nfactors=1,rotate=,scores=) #r:data,rotate default:maximum,scores default:no need 3.principal component rotation > rc<-principal(Harman23.cor$cov,nfactors=2,rotate="varimax") 4.get the score of the principal component > round(unclass(rc$weights),2) exploratory factor analysis 1.determine the number of common factors > library(psych) > covariances<-ability.cov$cov > correlations<-cov2cor(covariances) > fa.parallel(correlations,nobs=112,fa="both",n.iter=100, main="Scree plots with parallel analysis") 2.extracting common factor > fa<-fa(correlations,nfactors=2,rotate="none",fm="pa") 3.factor rotation > fa.varimax<-fa(correlations,nfactors=2,rotate="varimax",fm="pa") #orthogonal > fa.promax<-fa(correlations,nfactors=2,rotate="promax",fm="pa") #oblique > factor.plot(fa.promax,labels=rownames(fa.promax$loadings)) > fa.diagram(fa.promax,simple=FALSE) 4.factor score > fa.promax$weights
[I]Description 1.overall description summary() > summary(data) #min,lower quartile,median,upper quartile,max sapply() > sapply(x,FUN,options) #mean,standard deviation,skewness,kurtosis #options:mean(),sd(),var(),min(),max(),median(),length(),range(),quantile(),fivenum() describe() of Hmisc > describe(data) #variable and observation amount,missing value and unique value mean, #quantile,,five min,five max stat.desc() of pastecs > stat.desc(data) #- basic=TRUE(default) #variable,null value,missing value,min,max,range,summary #- desc=TRUE(default) #median,mean,mean standard deviation,mean confidence interval(confidence=95%) #- norm=TRUE #normal distribution,include skewness and kurtosis(and degree of statistics) describe() of psych > describe(data) #missing value mean,standard deviation,madian,trimmed mean, #median absolute deviation,min,max,range,skewness,kurtosis,standard error of the mean 2.part description aggregate() > aggregate(data,by=list(INDICES),FUN) #return single statistic by() > by(data,INDICES,FUN) #return multiple statistics summaryBy() of doBy > summaryBy(formula,data=dataframe,FUN=function) #single or multiple grouping variable layering #formula = var1 + var2 + var3 + ... + varN ~ groupvar1 + groupvar2 + ... + groupvarN #(varN is numerical variable,groupvar is grouping variable) describeBy() of psych > describeBy(data,list(INDICES)) #grouping variable are related 3.contingency table traditional Function Describe table(var1,var2, ... ,varN) N dimensional table xtabs(~formula,data) N dimensional table is based on a formula,a matrix or data frame generating prop.table(table,margins) convert frequency to scale margin.table(table,margin) summary addmargins(table,margins) add margins to table ftable(table) tiled contingency table CrossTable() of gmodels > CrossTable(data1,data2) [II]Test 1.known sample - independence Chi-square > chis.test(data) #p<0.01,related;p>0.05,unrelated Fisher percision > fisher.test(mytable) #mytable is not a 2×2 table Cochran-Mantel-Haenszel > mantelhaen.test(mytable) #no third-order interaction - correlation category type (1)Phi/Contingency/Cramer's V > assocstats(mytable) (2)Pearson/Spearman/Kendall > cor(x,use,method) #default:use="everything",method="pearson" > cov(data) #covariance > cor.test(x,y,alternative= ,method= ) #test a relationship at a time > corr.test(x,use,method) #test multiple relationships at a time use: all.obs:getting an error while getting wrong data; everything:missing is setting while missing data; complete.obs:line deletion pairwise.complete.obs:pairwise deletion method: pearson:linear correlation between two variables spearman:degree of correlation between graded variables kendall:level related measure (3)partial correlation > library(ggm) > pcor(u,S) #u:numerical vetor;S:covariance > pcor.test(r,q,n) #r:correlation coefficient;q:variable number;n:sample size continuous type (1)parameter1)independent sample > t.test(y~x,data) #t.test(y1,y2) 2)dependent sample > t.test(y1,y2,paired=TRUE) 3)more than two groups:ANOVA single factor varinance (y~A) > aov(formula,data=dataframe) > TukeyHSD() #pairwise comparison single factor covariance (y~x + A) double factors varinance (y~A * B) repeated measurement varinance (y~ B*W + Error(Subject/W)) multiple varinance > data->manova(y~A) > summary.aov(data) > Wilks.test(y,shelf,method="mcd") regression > fit.lm<-lm(y~A,data) > summary(fit.lm) (2)nonparameter two groups > wilcox.test(y~x,data) #wilco.text(y1,y2) more than two groups #groups independent > kruskal.test(y~A,data) #groups dependent >friedman.test(y~A|B,data) 2.random sample Function Description oneway_test(y~A) two samples and K samples oneway_test(y~A | C) containing a layering factor of two samples and K samples wilcox_test(y~A) Wilcoxon-Meann-Whitney kruskal_test(y~A) Kruskal-Wallis chisq_test(A~B | C) Pearson Chi-square cmh_test(A~B | C) Cochran-Mantel-Haenszel lbl_test(D~E) linear correlation spearman_test(y~x) Spearman friendman_test(y~A | C) Friendman wilcoxsign_test(y1~y2) Wilcoxon function_name(formula,data,distribution=) formula=variables relationship data=dataframe distribution="exact"/"asymptotic"/"approximate" Function Description lmp(A~B,data=,perm=) simple lmp(A~B+I(height^2),data=,perm=) polynomical lmp(A~B+C+D+E,data=,perm=) multiple avop(A~B,data=,perm=) single factor variance avop(A~B+C,data=,perm=) single factor covariance avop(A~B*C,data=,perm=) double factor variance perm="Exact"/"Prob"/"SPR" [III]efficacy Function Description pwr.2p.test(h=,n=,sig.level=,power=) two(n is equal) pwr.2p2n.test(h=,n1=,n2=,sig.level=,power=) two(n are not equal) pwr.anova.test(k=,n=,f=,sig.level=,power=) balanced single factor ANOVA pwr.chisq.test(w=,N=,df=,sig.level=,power=) Chi-square test pwr.f2.test(u=,v=,f2=,sig.level=,power=) generalized linear model pwr.p.test() proportion(single sample) pwr.r.test(n=,r=,sig.level=,power=,alternative=) correlation coefficient pwr.t.test(n=,d=,sig.level=,power=,type=,alternative=) t est(single sample/two samples/pair) pwr.t2n.test(n1=,n2=,d=,sig.level=,power=,alternative=) t test(n are not equal of two samples) h=ES.h(p1,p2) n=sample size $\mu$=mean $\sigma^2$=error variance sig.level=significant level(default=0.05) power=efficacy level k=groups number f=$\sqrt{\frac{\sum_{i-1}^{k}{p_i * {(\mu_i -\mu)}^2}}{\sigma^2}}$,$p_i=\frac{n_i}{N}$ w=$\sqrt{\sum_{i=1}^{m}{\frac{{(p0_i-p1_i)}^2}{p0_i}}}$,$p0_i=H_0$ for probability,$p1_i=H_1$ for probability N=total sample df=free degree u=N-B;N-k-1(k=forecast number) v=denominator free degree f2=$\frac{R^2}{1-R^2}$($R^2$=total squared value of multiple correlation); f2=$\frac{{R_{AB}}^2-{R_A}^2}{1-{R_{AB}}^2}$(${R_{A}}^2$=interpretation rate of A for total variance,${R_{AB}}^2$=interpretation rate of A and B for total variance) r=reference linear correlation coefficient alternative="two.sided"(default)/"less"/"greater" d=$\frac{\mu_1-\mu_2}{\sigma}$ type="two.sample"(default)/"one.sample"/"paired"END!
[I]symbols and lines > plot(A,B,type="b",lty=3,lwd=3,pch=15,cex=2) Parameter function pch plot point cex symbols size,default=1 lty lines type lwd lines weight,default=1 pch #plot pointcex #symbols size,default=1lty #lines typelwd #lines weight,default=1 Specially,symbol 21~25,can custom border color(by col=) and fill color(by bg=) [II]color #Create a color match > install.packages("RColorBrewer") > library(RColorBrewer) > n<-9 > mycolors<-brewer.pal(n,"Set1") > barplot(rep(1,n),col=mycolors) #multi-level grayscale > n<-9 > mycolors<-rainbow(n) > pie(rep(1,n),labels=mycolors,col=mycolors) > mygrays<-gray(0:n/n) > mygrays<-gray(0:n/n) > pie(rep(1,n),labels=mygrays,col=mygrays) Parameter function col plot color col.axis axis scale text color col.lab axis label color col.main main title color col.sub sub title color fg foreground bg background Color Number Hex RGB "white" 1 "#FFFFFF" rgb(1,1,1) "black" 24 "#000000" rgb(0,0,0) "bule" 26 "#0000FF" rgb(0,0,255) "brown" 32 "#A52A2A" rgb(165,42,42) "orange" 498 "#FF6100" rgb(255,215,0) "pink" 536 "#FFC0CB" rgb(255,192,203) "purpel" 547 "#800080" rgb(128,0,128 "red" 552 "#FF0000" rgb(255,0,0) "yellow" 652 "#FFFF00" rgb(255,255,0) [III]text > opar<-par(no.readonly=TRUE) > par(font.lab=3,cex.lab=1.5,font.main=4,cex.main=2) > par(opar) Parameter function cex text size cex.axis axis scale size cex.lab axis label size cex.main main title size cex.sub sub title size Parameter function font 1=Normal,2=Bold,3=Italic,4=Bold Italic,5=Symbol Font font.axis axis scale font font.lab axis label font font.main main title font font.sub sub title font pa font value(1pound=1/72inch),font vale=ps*cex family drawing text,value=serif/sans/mono [IV]graphic size and boundary size > opar<-par(no.readonly=TRUE) > par(pin=c(4,3),mai=c(1,5,1,2)) > par(opar) Parameter function pin graphic size:width and height(inch) mai boundary size:up down left right(inch) mar boundary size:up down left right(British cent),default=c(5,4,4,2)+0.1 [V]title > title(main="My Title",col.main="red", + sub="My Subtitle",col.sub="blue", + xlab="My X label",ylab="My Y label", + col.lab="green",cex.lab=0.75) [VI]axis > axis(4,at=z,labels=round(z,digits=2),col.axis="blue",las=2,cex.axis=0,7,tck=-0.1) Parameter function side the relative position of the axis in the graph,1=down,2=left,3=up,4=right at scale position labels scale line text label pos intersecting another axis position value lty lines type col lines and scale lines color las 0=label is parallel to the coordinate axis,2=label is perpendicular to the axis tck 0=disable scale,1=plot grid lines,default=-0.01 [VII]reference line > abline(h=c(1,5,7),v=seq(1,10,2),lty=2,col="bule") [VIII]legend > legend("top;eft",inset=.0.5,title="Music Type",c("A","B"),lty=c(1,2),pch=c(15,17),col=c("red","bule")) Parameter function location legend positon,bottom,bottomleft,left,topleft,top,topright,right,bottomright,center title legend title string legend legend label string vector [IX]text annotation > text(age,ID,row.names(singerdata),cex=0.6,pos=4,col="red") Parameter function location text position pos relative position of text,1=down,2=left,3=up,4=right,offset can be set side text side,1=down,2=left,3=up,4=right,adj=0:align left bottom,adj=1:align right bottom math annotation [X]graphics combination #par() > par(mfrow=c(2,2)) #layout() > layout(matrix(c(1,1,2,3),2,2,byrow=TRUE),widths=c(3,1),heights=c(1,2)) [XI]ggplot2 1.specify the type of graph with a geometry function Function Add Option geom_bar() bar chart color,fill,alpha geom_boxplot() box plot color,fill,alpha,notch,width geom_density() density plot color,fill,alpha,linetype geom_histogram() histogram color,fill,alpha,linetype,binwidth geom_hline() horizontal line geom_jitter() jitter point color,size,alpha,shape geom_line() line plot colorvalpha,linetype,size geom_point() scatter plot color,alpha,shape,size geom_rug() carpet plot color,side geom_smooth() curve fitting method,formula,color,fill,linetype,size geom_text() text annotation reference to "help" geom_violin() violin picture color,fill,alpha,linetype geom_vline() perpendicular color,alpha,linetype,size 2.grouping > data(Salaries,package="car") > library(ggplot2) > ggplot(data=Salaries,aes(x=salary,fill=rank)) + geom_density(alpha=,3) > ggplot(Salaries,aes(x=yrs,.since.phd,y=salary,color=rank,shape=sex))+geom_point() > ggplot(Salaries,aes(x=rank,fill=sex)) + geom_bar(position="stack")+ labs(title='position="stack"') > ggplot(Salaries,aes(x=rank,fill=sex)) + geom_bar(position="dodge")+ labs(title='position="dodge"') > ggplot(Salaries,aes(x=rank,fill=sex)) + geom_bar(position="fill")+ labs(title='position="fill"') > ggplot(Salaries,aes(x=rank,fill=sex)) + geom_bar() > ggplot(Salaries,aes(x=rank)) + geom_bar(fill="red") > ggplot(Salaries,aes(x=rank,fill="red‘’)) + geom_bar() 3.characterize Grammar Result facet_wrap(~var,ncol=n) arrange each var horizontally into an independent map of n columns facet_wrap(~var,nrow=n) arrange each var horizontally into an independent map of n rows facet_grid(rowvar~colvar) independent plot of rowvar and colvar facet_grid(rowvar~.) independent plot of each rowvar level,configured as a single column facet_grid(.~colvar) independent plot of each column level,configured as a single row 4.add a smooth curve Option Description method= default=smooth;lm,smooth,rlm,gam formula= y~x(default),y~log(x),y~poly(x,n),y~ns(x,n) se draw a confidence interval,default=TRUE level confidence interval level used,default=95% fullrange default=FALSE:just data;TRUE:the fit should cover the full picture 5.appearance (1)axis Functions Option scale_x_continuous()&scale_y_continuous break,label,limits,=specified scale_x_discrete()&scale_y_discrete() break,label,limits,=level coord_flip() reverse the x and the y axes (2)legend > data(Salaries,package="car") > library(ggplot2) > ggplot(data=Salaries,aes(x=rank,y=salary,fill=sex)) + geom_boxplot() + scale_x_discrete(breaks=c("AsstProf"),"AssocProf","Porf"), labels=c("Assistant\nProfessor","Associate\nProfessor","Full\nProfessor"))+ scale_y_continuous(break=c(50000,100000,150000,200000), lables=c("$50K","$100K","$150K","$200k"))+ labs(title="Faculty Salary by Rank and Gender",x="",y="",fill="Gender")+ theme(legend.position=c(.1,.8)) (3)ruler > ggplot(mtcars,aes(x=wt,y=mpg,size=disp))+geom_point(shape=21,color="black",fill="cornsilk")+ labs(x="Weight",y="Miles Per Gallon",title="Bubble Chart",size="Engine\nDisplacement") > data(Salaries,package="car") > ggplot(data=Salaries,aes(x=yrs.since.phd,y=salary,color=rank))+ scale_color_manual(values=c("orange","olivedrab","navy"))+geom_point(size=2) > ggplot(data=Salaries,aes(x=yrs.since.phd,y=salary,color=rank))+ scale_color_brewer(palette="Set1")+geom_point(size=2) > library(RColorBrewer) > display.brewer.all() (4)theme > data(Salaries,package="car") > library(ggplot2) > mytheme<-theme(plot.title=element_text(face="bold.italic",size="14",color="brown"), axis.title=element_text(face="bold.italic",size=10,color="brown"), axis.text=element_text(face="bold",size=9,color="darkblue"), panel.background=element_rect(fill="white",color="darkblue"), panel.grid.major.y=element_line(color="grey",linetype=1), panel.grid.minor.y=element_line(color="grey",linetype=2), panel.grid.minor.x=element_blank(),legend.position="top") > ggplot(Salaries,aes(x=rank,y=salary,fill=sex))+geom_boxplot()+ labs(title="Salary by Rank and Sex",x='Rank",y="Salary")+mytheme (5)multiple map > data(Salaries,package="car") > library(ggplot2) > p1<-ggplot(data=Salaries,aes(x=rank))+geom_bar() > p2<-ggplot(data=Salaries,aes(x=sex))+geom_bar() > p3<-ggplot(data=Salaries,aes(x=yrs.since.phd,y=salary))+geom_point() > library(gridExtra) > grid.arrange(p1,p2,p3,ncol=3) 5.save > myplot<-ggplot(data=mtcars,aes(x=mpg))+geom_histogtam() > ggsave(file="mygraph.png",plot=myplot,withd=5,height=4) > ggplot(data=mtcars,aes(x=mpg))+geom_histogram() > ggsave(file="mygraph.pdf") END!
[I]Data Structure 1.vector numeric > a<-c(1,2,3) > a [1] 1 2 3 character > a<-c("1","2","3") > a [1] "1" "2" "3" logicals > a<-c(FALSE,TRUE) > a [1] FALSE TRUE scalar > a<-FALSE > a [1] FALSE 2.matrix create #base > mymatrix<-matrix(1:9,nrow=3,ncol=3) > mymatrix [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 #labeling rows/cols > cells<-c(1:9) > rnames<-c("R1","R2","R3") > cnames<-c("C1","C2","C3") > mymatrix<-matrix(cells,nrow=3,ncol=3,byrow=TRUE,dimnames=list(rnames,cnames)) #fill according to row > mymatrix C1 C2 C3 R1 1 2 3 R2 4 5 6 R3 7 8 9 > mymatrix<-matrix(cells,nrow=3,ncol=3,byrow=FALSE,dimnames=list(rnames,cnames)) #fill according to column > mymatrix C1 C2 C3 R1 1 4 7 R2 2 5 8 R3 3 6 9 index > mymatrix[2,] C1 C2 C3 2 5 8 > mymatrix[,2] R1 R2 R3 4 5 6 > mymatrix[2,2] [1] 5 > mymatrix[2,c(1,2)] C1 C2 2 5 3.array > dim1<-c("A1","A2","A3") > dim2<-c("B1","B2","B3") > dim3<-c("C1","C2","C3") > myarry<-array(1:27,c(3,3,3),dimnames=list(dim1,dim2,dim3)) > myarray , , C1 B1 B2 B3 A1 1 4 7 A2 2 5 8 A3 3 6 9 , , C2 B1 B2 B3 A1 10 13 16 A2 11 14 17 A3 12 15 18 , , C3 B1 B2 B3 A1 19 22 25 A2 20 23 26 A3 21 24 27 4.data frame create > ID<-c(1,2,3,4) > age<-c(27,26,32,54) > sex<-c("Male","Female","Female","Female") > music<-c("Type2","Type1","Type1","Type1") > status<-c("Excellent","Improved","Poor","Excellent") > singerdata<-data.frame(ID,age,sex,music,status) > singerdata ID age sex music status 1 1 27 Male Type1 Excellent 2 2 26 Female Type2 Improved 3 3 32 Female Type1 Poor 4 4 54 Female Type1 Excellent select #base > singerdata[1:2] ID age 1 1 27 2 2 26 3 3 32 4 4 54 > singerdata[c("music","status")] music status 1 Type2 Excellent 2 Type1 Improved 3 Type1 Poor 4 Type1 Excellent > table(singerdata$music,singerdata$status) Excellent Improved Poor Type1 1 1 1 Type2 1 0 0 #external data:e.g.mtcars > attach(mtcars) #No object of the same name > summary(mpg) Min. 1st Qu. Median Mean 3rd Qu. Max. 10.40 15.43 19.20 20.09 22.80 33.90 > plot(mpg,disp) > detach(mtcars) > with(mtcars,{ #object of the same name + nokeepstats<-summary(mpg) + keepstats<<-summary(mpg) + }) > nokeepstats #internal call Error: object 'nokeepstats' not found > keepstats #external call Min. 1st Qu. Median Mean 3rd Qu. Max. 10.40 15.43 19.20 20.09 22.80 33.90 5.factor > ID<-c(1,2,3,4) > age<-c(27,26,32,54) > sex<-c(1,2,2,2) > music<-c("Type1","Type2","Type1","Type1") > status<-c("Excellent","Improved","Poor","Excellent") > sex<-factor(sex,levels=c(1,2),labels=c("Male","Female")) #label replace > music<-factor(music) #default order:A-Z > status<-factor(status,order=TRUE,levels=c("Poor","Improved","Excellent")) #customize order > singerdata<-data.frame(ID,age,sex,music,status) > str(singerdata) 'data.frame': 4 obs. of 5 variables: $ ID : num 1 2 3 4 $ age : num 27 26 32 54 $ sex : Factor w/ 2 levels "Male","Female": 1 2 2 2 $ music : Factor w/ 2 levels "Type1","Type2": 1 2 1 1 $ status: Ord.factor w/ 3 levels "Poor"<"Improved"<..: 3 2 1 3 > summary(singerdata) ID age sex music status Min. :1.00 Min. :26.00 Male :1 Type1:3 Poor :1 1st Qu.:1.75 1st Qu.:26.75 Female:3 Type2:1 Improved :1 Median :2.50 Median :29.50 Excellent:2 Mean :2.50 Mean :34.75 3rd Qu.:3.25 3rd Qu.:37.50 Max. :4.00 Max. :54.00 6.list create > tit<-"singer list" > name<-c("Hua","Deng","Ga","Wang") > age<-c(27,26,32,54) > position<-matrix(1:9,nrow=3) > mylist<-list(title=tit,name,ages=age,position) > mylist $title [1] "singer list" [[2]] [1] "Hua" "Deng" "Ga" "Wang" $ages [1] 27 26 32 54 [[4]] [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 index > mylist[[2]] [1] "Hua" "Deng" "Ga" "Wang" > mylist[["ages"]] [1] 27 26 32 54 [II]Import Data 1.keyboard text editor > mydata<-data.frame(age=numeric(0),sex=character(0),order=numeric(0)) > mydata<-edit(mydata) #reopen:> mydata<-edit(mydata) result: embedded > mydatatxt<-" + age sex order + 27 Male 1 + 26 Female 2 + 32 Female 3 + 54 Female 4 + " > mydata<-read.table(header=TRUE,text=mydatatxt) > mydata age sex order 1 27 Male 1 2 26 Female 2 3 32 Female 3 4 54 Female 4 2.delimited text file singerdata.csv > music<-read.table("singerdata.csv",header=TRUE,row.names="ID",sep=",",colClasses=c("character","character","numeric","character","numeric")) > music name age sex music 1 Hua 27 Male 100 2 Deng 26 Female 95 3 Ga 32 Female NA 4 Wang 54 Female 93 > str(music) 'data.frame': 4 obs. of 4 variables: $ name : chr "Hua" "Deng" "Ga" "Wang" $ age : num 27 26 32 54 $ sex : chr "Male" "Female" "Female" "Female" $ music: num 100 95 NA 93 3.Excel > install.packages("xlsx") > install.packages("xlsxjars") > install.packages("rJava") > library(xlsx) > workbook<-"c:/myworkbook.xlsx" > mydatdaframe<-read.xls(workbook,1) 4.XML RSXML 5.web page Webscraping using readLines and RCurl 6.SPSS > install.packages("Hmisc") > library(Hmisc) > mydataframe<-spss.get("mydata.sav",use.value.labels=TRUE) 7.SAS #installed SAS > install.packages("Hmisc") > library(Hmisc) > datadir<-"C/data" > sasexe<-"C/Program Files/SASHome/SASFoundation/9.4/sas.exe" > mydata<-sas.get(libraryName=datadir,member="clients",sasprog=sasexe) #not installed SAS > install.packages("sas7bdat") > library(sas7bdat) > mydata<-read.sas7bdat("C:/mydata/clients.sas7bdat") 8.Stata > install.packages("foreign") > library(foreign) > mydataframe<-read.dta("mydata.dta") 9.NetCDF > install.packages("ncdf4") > library(ncdf4) > myarray<-ncatt_get(nc,varid) 10.HDF5 > source("http://bioconductor.org/biocLite.R") > biocLite("rhdf5") > library(rhdf5) > h5ls("C:/mydata") 11.data management system ODBC API > install.packages("RODBC") > library(RODBC) > myconn<-odbcConnect("mydsn",uid="xw",pwd="xinwenfan") > crimedat<-sqlFetch(mymonn,Crime) > pundat<-sqlQuery(myconn,"select* from Punishment") > close(myconn) DBIThe Comprehensive R Archive Network 12.Stat/Transfer [III]Object Function > length(object) #the number of elements/ingredients in the object > dim(object) #dimension of object > str(object) #structure of object > class(object) #type of object > mode(object) #type of object > names(object) #name of ingredients > c(object,object,...) #binding objects into one vector > cbind(object,object,...) #binding objects by column > rbind(object,) #binding objects by row > object #printing object > head(object) #listing the beginning part > tail(object) #listing the ending part > ls() #show current list ---- [IV]Generate dynamic reports by R and LaTex 1.install LeTex Linux:TeXLiveWindows:MikTexMac:MacTeX 2.install knitr > install.packages("knitr") 3.install data package #e.g.multcomp > install.packages("multcomp") 4.Creat File.Rnw #e.g. drugs.Rnw 5.process data > library(knitr) > knit("drugs.Rnw") #drugs.tex > knit2pdf("drugs.Rnw") #drugs.pdf END!
谈及智能控制方法,很多研究还是在做控制算法的优化,但到目前控制领域乃至整个人工智能领域所面临的两个重大瓶颈其实是存储器和中央处理器分离“冯诺依曼”架构导致的存储墙效应造成能效低下,和引领半导体发展的摩尔定律预计在未来数年内失效。针对这两个问题,未来更适用的智能控制方法,显而易见,应该是基于非冯诺依曼架构的类脑计算控制方法。在类脑计算领域有三大板块,第一,类脑计算算法、芯片、软件工具链和系统;第二,接口;第三,应用。结合此篇论文,主要说明我对类脑计算算法、芯片以及应用方面的感想。 一、类脑计算算法 之前在总结各种智能算法时,我试着对比真实宇宙与数码世界,后来发现人脑和电脑用基本的原理是正好相反的。真实世界中,每一层都支撑上一层,但数码宇宙却是每一层回到最底层。目前的人工神经网络,只是借助了空间复杂性的描述,完成一种傻瓜式的映射。而对于真正的大脑,一个神经元接一千个一万个神经元。这是扩和缩的概念,计算机是缩,脑是扩,所以最终处理信息的时候是非常快的,所以我们想建立一个一样的架构,就要让计算机的架构保持类脑复杂性。 在物理学角度,这是熵的增减问题,反映到计算机上,这就产生了,能耗、速度和带宽等一系列问题。因为广义的通用系统,需要控制的元素太多了,而现如今我们的认知能力又有限并且水平不一,所以按照传统智能算法,得出的结论是参差不齐的。所以想提高准确度与认知能力,必须要结合时间和空间空的复杂度,而最有效的方法,不是一味的追求理论上的准确度,而是试错,试错是人类一个非常非常重要的能力。所以训练一个算法模型主要采用通过环境刺激和交互训练实现感知认知等基础性智能,其效率更高,获得的智能也更适应复杂环境。把时空复杂性结合起来,也就是把空间的编码和时间的编码结合起来,是把一个多维空间的信息转换成0101这样一个的信息量,主频越来越快,这正是编码算法的多维性。 二、类脑计算芯片 类脑计算机的基本元器件是模拟生物神经元和突触的神经形态器件,其特征尺寸与生物对应物相当或更小,不仅可比晶体管更小,而且部分器件出错不影响系统基本功能。我所了解到目前国内类脑芯片研究成果比较出色的有,寒武纪的类脑智能芯片和清华大学类脑计算中心的天机芯。我在看这些芯片基础资料的同时,了解到,类脑智能芯片发展主要背景的几项技术,这也未来几年智能芯片发展的核心依托技术。1.先进测量计算的发展,对脑的认识越来越清楚,似乎到了一个拐点,就是人类真正理解脑基本的机制。2.超级计算机的发展,可以做很多的仿真,省时、省力、省时间。3.云计算和互联网提供了一个足够复杂的系统,给人进行交付,互动、学习,同时它的发展给我们很多的启示,使我们对它有很好的理解。4.纳米器件的发展,已经可以做出和人脑能耗差不别级别的器件。也正是各行各业的技术,一起崛起,让我意识到技术的发展,同人的发展一样,不是要往独当一面的方向发展,而是相互融合的,对于类脑智能,它必须是精密仪器、医学、计算机、自动化、微电子、电子和材料等学科知识相互渗透,相互复合而来。 三、类脑计算应用 一直站在学生的角度看世界,不免对教育有很多看法,其实也只有学生才能深刻的认识教育所面临的问题,比如,教育资源不公平,不能因材施教,理论不联系实际等等。学过了很多智能算法,有没有一种可以颠覆现在的教育系统,根据我们学生的真实需求而受教育呢?我希望类脑计算能,不仅能作为未来认知智能时代,万物智联的主要手段,还能推动教育方式的改革,用思维改进技术,用技术改变思维。当然,在类脑计算领域中自主开发软件工具链和类脑计算系统也非常重要。其中目前所涉及的智能算法,还只是通用人工智能的算法,软件开发也是基于Tensorflow架构的。所以,我们在类脑计算模型方向的研究还任重道远,也是迫切需要自主解决的,希望未来自己能在这个方向有所突破。
1.语音情感计算中情感的建模方法有哪些?有什么区别?情感计算主要应用于哪些领域? 支持向量机(SVM)、隐马尔可夫模型(HMM)、人工神经网路(NN)等。 SVM:基音+SVM算法=统计特征→识别语音状态; HMM:输入特征矢量序列+训练=统计信号→识别语音状态; NN:多层神经网路+训练=模拟人脑组织→识别语音状态。 虚拟人物、身份验证、智能用户界面、交互式感性图像检索、多功能机、语音识别、面部识别、军用可穿戴计算机等等。 2.列举三种以上的用于语音情感计算的声学特征,并解释其物理含义。 声学特征: 音色。发音体形状、质地、构造不同,决定了音色的不同。 音调。发音体声音频率的高低。 音强。发音体振动的幅度特征。 音长。发音体振动延续的时间特征。 语句特征: 基频。基音的频率,决定了音高。在不同情感状态说,说同一段话,基频是不同的。一般研究基频的峰值、均值、方差等特征。 低于250HZ的谱能量。根据parseval定理,信号傅氏变换模平方被称为谱能量。带有情绪的状态下谱能量和低于250HZ的谱能量时的存在一些规律。 语速。讲一个语句的速度。不同情绪下的语速有规律性差异。 能量。生气和高兴时能量高,其次平静,悲伤最低。
LabView串口通信 LabView通过VISA能与GPIB、USB、串口等大多数仪器总线连接。 一般的串口控制步骤是: 配置串口; 读写串口; 关闭串口。 配置串口 具体实例如下所示:图下方的while循环表明,如果没有选择端口,则不可读取数据。 数据读取处理 首先读取数据; 显示出数据所描述的波形,得出单频测量模块的频率测量值; 用三点法得出测量频率值; 多周期计数法计测量脉搏信号; 对测量所得数据处理及显示。 1. bytes at port确定字节数 这个组合的功能是,读取VISA串口已有的全部数据。组合的前面,是 VISA 串口字节数,函数路径见上图。bytes at port 利用一个读取缓冲区字节数,读取到字节数,确定了 VISA要 读取的字节数,然后再通过读取 VISA 读出来。简而言之,前面的先侦测下串口缓冲区有多少数据,侦测完后告诉 VISA 读,VISA就全读出来。 2.Build Waveform 读取数据后波形出来是个簇,包含三个分量:Y是波形数据,dt是时间间隔。构建波形后,通过后面的测量模块可得到脉搏测量频率。 3.延时模块 此部分是为了释放电脑核心,一个循环会占用CPU的一个核心,如果不加掩饰,配置低的电脑容易卡死。 4.交流电路参数测量——三点法 这里采用时域方法——三点法处理。三点法:建立在三角函数变换基础上的数据拟合方法。 假设被测函数是正弦函数,在等间隔采样的前提下(包括非整周期采样)可以利用相邻3个数据样本,导出求解信号频率的线性方程,进而拟合出方程系数,最后求出频率。 N个样本,最小二乘法拟合可以得到一个较准确的cosθ。 函数:Linear Fit Coefficients。 一言以蔽之,取数组里面的3个数,将数1和数3相加,其作为曲线拟合的X,再把数2乘2作为曲线拟合的Y,得出斜率后,再做反余弦,反余弦后乘缩小100(采样频率)的两倍π,最后得出结果。 5.交流电路参数测量——多周期计数法产生方波信号 采用多周期计数法,可以采用阈值法,将脉搏信号转化成方波信号,再进行后续处理。数组的数量为for循环的次数,而后均值与数组中的数做比较,均值若大于数组中数则输出布尔值T,否则为F,从而后构建成方波信号。 6.交流电路参数测量——多周期计数法判断信号开始结束 多周期计数法还需要判断一个周期的开始和结束,可采用过零法和阈值法,此例采用阈值法。若数组相邻索引值正好构成一个周期内的方波信号,则给选择结构的条件为真,输出索引数据,反之输出0。 7.交流电路参数测量(4) 数组索引的数相即为最终采样数据,相邻两个样本的差值即为当前周期的样本数,乘以采样周期,再取倒数,即为一个周期内的样本数。 然后取多个周期,再取均值,即作为最后的频率测量值。m个周期的均值: 每分钟脉搏次数 = 脉搏频率 × 60s。 8.结束程序 因为整个程序有两个循环,但只有一个结束按钮,如果直接挂局部变量,会报布尔动作的错误,所以采用此种形式。 关闭串口 关闭串口,即通信结束。 整体展示 前面板 后面板 此程序整体采用顺序结构,把演示放在帧里还有一个好处是,循环开始时,先延时在开始后面循环里的程序。 END!
PCF8951+I2C+STC89C52 ADC采集与输出 I2C IIC是一种多向控制总线,也就是说多个芯片可以连接到同一总线结构下,同时每个芯片都可以作为实时数据传输的控制源。主要包括启始、停止、读、写、应答信号。这种方式简化了信号传输总线接口。 IIC总线上可以挂多个器件,而每个器件都有唯一的地址,这样可以标识通信目标。数据的通信的方式采用主从方式,主机负责主动联系从机,而从机则被动回应数据。 1.I2C总线信号 (1)开始和停止信号 开始信号:SCL=1,SDA下降沿; void start() { SDA = 1; //初始时,SDA=1 SCL = 1; //初始时,SCL=1 delay(); //保持时间大于4.7us SDA = 0; //SDA下降沿 delay(); //SDA下降沿保持时间大于4.0us } 停止信号:SCL=1,SDA为上升沿。 void stop() { SDA = 0; //初始时,SDA=0; SCL = 1; //初始时,SCL=1; delay(); //保持时间大于4.0us SDA = 1; //SDA上升沿 delay(); //保持时间大于4.7us } (2)应答信号 void ack() { uchar i = 0; //定义缓冲变量 SCL = 1; delay(); while(SDA == 1 && i < 250)i++; //稳定时间大于4us SCL = 0; //SCL=0时,SDA数据才可以改变 delay(); } 2.I2C总线数据传输条件 SCL=1时,SDA必须保持稳定; SCL=0时,SDA才允许改变。 3.I2C总线读写操作 (1) 数据传送规则: 每传送一个字节时必须保证是8位长度; 数据传送时,先传送最高位(MSB); 每个被传送的字节后面,跟随一位应答信号,即一帧实际共有9位。 (2)数据传送流程: 主机向总线发送一个字节的数据后,释放总线,从机拉低总线(即应答信号),表示这一字节发送成功; 主机从总线读取完一个字节的数据后,主机把总线拉低,表示这一字节发送成功。 a.写入数据 void write_byte(uchar dat) { uchar i; for(i = 0; i < 8; i++) { dat = dat << 1; //先写最高位,通过左移运算符,将一个字节的数据一位一位的传送到总线上 SCL = 0; //SCL=0,从机准备接收数据 delay(); SDA = CY; //CY存储的是左移后的进位 delay(); SCL = 1; delay(); } SCL = 0; //8位数据传输完后,释放SDA,准备接收应答位 SDA = 1; // 释放SDA delay(); } b.读取数据 uchar read_byte() { uchar dat = 0, tmp, i; SCL = 0; //SCL=0,准备接收数据 delay(); for(i = 0; i < 8; i++) { SCL = 1; //SCL = 1,SDA稳定,准备读取数据 delay(); tmp = SDA; //读取此时SDA的状态 dat = dat << 1; //先写最高位,通过左移运算符,将一个字节的数据一位一位的传送到总线上 dat = dat | tmp; //读数据位,接收的数据位放在dat中 delay(); SCL = 0; //释放SDA总线,为下一次读取做准备 delay(); } return dat; // 返回读取的dat值 } 4.I2C总线初始化 void I2C_init() { SDA = 1; delay(); SCL = 1; delay(); } PCF8951 PCF8591是单片、单电源低功耗8位CMOS数据采集器件,具有4个模拟输入、一个输出和一个串行I2C总线接口。3个地址引脚A0、A1 和A2 用于编程硬件地址,允许将最多8个器件连接至I2C总线而不需要额外硬件。器件的地址、控制和数据通过两线双向I2C总线传输。器件功能包括多路复用模拟输入、片上跟踪和保持功能、8位模数转换和8位数模拟转换。最大转换速率取决于I2C总线的最高速率。 1.器件地址 总线启动后,发送的第一个字节。由电路原理图可知,A0 A1 A2均为0,所以: lsb=0时,即器件地址为0x90时,表示主机向从机写数据,下一个字节向总线写入数据; lsb=1时,即器件地址为0x91时,表示主机从从机读数据,下一个字节从总线读取数据。 2.控制字 总线启动后,发送的第二个字节。 msb,默认为0; 第6位,选择是否允许模拟电压输出,DA转换时设置为1,AD转换时设置为0或1均可; 第5/4位,选择模拟电压输出方式; 第3位,默认为0; 第2位,是自动增量使能位,设置1后,每次A/D 转换后通道号将自动增加; 第1/0位,是在AD转换时选择输入的电压转换为数字量的通道。 3.ADC 将AIN端口输入的模拟电压转换为数字量并发送到总线上。 uchar Read_D(uchar Channel) { uchar dat; //定义缓存变量 start(); //启动I2C总线 write_byte(0x90); //向总线写入从机地址09x0,表示下一个字节向总线写入数据 ,+0,主机发送数据 ack(); //应答信号 write_byte(Channel); //向总线写入控制字Channel表示通道1 ack(); //应答信号 start(); //重复启动I2C总线,读写方向和上一次相反 write_byte(0x91); //向总线写入从机地址09x1,表示下一个字节从总线读取数据 ,+1,主机接收数据 ack(); //应答信号 dat=read_byte(); //读取数据并赋给变量dat ack(); //应答信号 stop(); //停止I2C总线 return dat; //返回读取的数据值 } 4.DAC 将从总线上接收到的数字量通过AOUT输出。 void Out_A(uchar Digital) { start(); //启动I2C总线 write_byte(0x90); //向总线写入主机地址09x0,表示下一个字节向总线写入数据,+0,主机发送数据 ack(); //应答信号 write_byte(0x40); //向总线写入控制字0x40,允许模拟输出,不自增单端,通道0 ack(); //应答信号 write_byte(Digital); //向总线写入要转换的数字量Digital ack(); //应答信号 stop(); //停止I2C总线 } 主函数 void main() { I2C_init() ; //I2C总线初始化 dat1 = Read_D(0x01); //将通道1的模拟量转化为数字量,并读取 delay(); Out_A(dat1); //将数字量转化为模拟量输出 delay(); } END!
“真爱也许没有先后,但是陪伴是会有的,人生就那么长,不论何时才能和你走到一起,我都愿意等,只是这个在一起,我永远不希望是牺牲了别人的幸福而得到。” 故事主角小拉、小傅和小Z,如果你只想知道结局: THE END! 正经的gossip 接下来将以傅立叶分析为切入点,分享我所理解的信号处理中拉普拉斯变换、傅立叶变换和Z变换这三大变换之间的关系(0基础也能看懂,只要有颗八卦的心)。 傅立叶分析是什么? 无穷多的信号在时间域和频率域之间的转换。 1)无穷多,就是很多很多。2)信号,形式千变万化,但都可以用无穷多的正弦波叠加而成。3)时间域,从起床闹钟开始,到几点该做什么,都是用时域在把控。4)频率域,声音振动频率不同决定了音调高低,音域就是频率域的一种。 正弦波怎么叠加出各式样的信号? 1)什么是正弦波? 看了维基百科这个生动形象的图后,还有不明白的吗?So,我们就可以认为,正弦波是圆周运动在一条直线上的投影。 2)正弦波叠加后是怎样的?当年小拉和小傅吵架说,正弦曲线无法组合成一个带有棱角的信号。那接下来我就举个最普通的栗子,用正弦波叠加出矩形波,为小傅平反。 上图中,我们有两点需要注意。正弦波只能叠加出一个无限接近的矩形波。极限的思想就是告诉我们,就算不断努力积累,还是达不到极限。从时域到频域的转换是不是一目了然,虽然到这,还是不清楚转换的本质,但是基本转换的过程应该是有一定的理解了。所以,有人肯定发现我骗了你,老师说过,正弦波的三要素是,幅值、频率和初相角,现在只有幅频图,相频图呢?好吧,继续看图: 距离频率轴最近的波峰的值我们称为时间差,这里假设,合成矩形波的周期为2π,每条正弦波的时间差除以本身的周期再乘以合成波的周期2π,就得到了相位差。又因为正弦波是周期函数,所以我们一般认为相位差的值域是[-π,π]。我目前常用的分析幅相特性的方法有:上述所用的直角坐标表示法和极坐标下的Nyquist曲线、对数坐标系下的Bode图、Nichols图,这些方法都挺好用的,但是这里就不一 一八卦了。以上这段简单的分析中,原信号在时域中是连续周期的函数,转化到频域中是非周期离散的,这种变换就是傅立叶分析中的傅立叶级数。 傅立叶分析具体有哪些? 处理不同形式的信号,采用的方法肯定不同,所以有了多变的傅立叶: 对于傅立叶变换,可以看成是对一个周期无限大的连续信号先进行傅立叶级数,再把频域离散的幅相曲线转换为连续的,在数学运算中,就是把加变成积分。BUT,计算机能处理什么信号?没错,数字信号,是连续的吗?当然不,是离散信号。So,刚整明白的傅立叶变换和傅立叶级数,是对计算机不适用的。是不是有点迷茫了,要相信,人生没有白走的路,只是说不适用,但是可以此为基础,根据实际情况摸索属于自己的路。 我们先来看下离散信号和连续信号之间的关系: 看明白上图后继续BUT,貌似还不对哦,计算机能处理无穷的信号吗?不能吧,所以上面说的DTFT和DFS还是不适用。不曾迷茫过又怎会清醒,现在的你应该终于明确了,计算机只能处理离散有限长的信号,而处理方法称为离散傅立叶变换(DFT)。实际应用中,当接收到时域连续的模拟信号,首先以频率进行采样将信号离散,然后用通过DTFT截取信号的主值周期,然后用DFS进行周期延拓,最后进行DFT得到频域的信号。 你以为这就完了? 复数域的傅立叶变换是什么? 复数是什么? 1)什么是虚数? 我不知道这个问题有没有意义,但是当年读中学时,还问过老师为什么$i^2=-1$,她至今也没回答我。。。就像初中以前我还只知道正数,而1-2=?,不存在的,那个时候我以为的数轴是这样的: 后来,老师告诉我1-2可以=-1了,当时我还问过我妈,1毛钱怎么买2毛的拖肥呢?去商店尝试之后,从此负数给我的印象就是欠下的债。所以我像发现新大陆一样,又知道了数轴原来是这样的: 2)刚以为自己世界无敌了,谁知道哪天又蹦出来个虚轴,绝望!!! 生活总是这样瞬息万变的,像奥特曼超人说的那样:“坚持不变的根本,去应对多变的行业(这里可以延伸到生活)。保持对‘优秀’的敬畏之心!每天一个脚印向前迈。”也只能这么安慰自己了。 不要抱怨老师为什么不一次性把话说全,而且一个喘气就是几年。学习过程大都是循序渐进的,由正数→负数→复数的过程,是由数的本质决定的。比如+1在数轴上,它可以表示方向向右、长度为1的向量,将它的起点固定,逆时针旋转180度,就得到了-1,负数就这么来了。那虚数怎么来的呢?根据上面的坐标轴:正数绕点(0,0)逆时针旋转90度的奇数倍就是虚数,这里把正数绕点(0,0)逆时针旋转90度用虚轴的基i来描述,可以把他理解为基本单位或者是奥特曼说的不变的根本。所以上面的栗子可以煮成: (+1)*(逆时针旋转180度)=-1, So,(逆时针旋转180度)=-1, So,i×i=-1, So,我终于懂为什么了。 所以从此,我概念里的数,便又多了由实数和虚数组成的复数。而前面的信号都是基于实数的,复数是不适用,但原理都是一样的,只是数的性质改变了。 就像人生不同阶段会遇到不一样的人,面临不同程度的选择,就像沙漠里,有人选择寻骆驼,有人等花开,以致到最后,连自己都成了过客,自己也不再是同一个自己。So,下一个主角该上场了。 实数怎么变化到复数? 这个变化关系就是被称为最帅的数学公式之一的欧拉公式: $e^{j{\theta}}=cos{\theta}+jsin{\theta}$ 在图中,能看到$e^{-{j{\theta}}}=cos{\theta}-jsin{\theta}$不?看不到就再好好看看吧,这两个公式相加,整理后可以得到:$cos{\theta}=\frac{e^{j{\theta}}+e^{-{j{\theta}}}}{2}$。这里直接分析时域里的复数信号喽,在复平面,横轴表示实数,纵轴表示虚数,信号的幅值肯定是个落在横轴上的实数,而相角$\theta=wt={\frac{2\pi}{T}}t=2{\pi}ft$,则是不断变化的,所以,信号在复平面内是随着时间的变化呈现出螺旋线状的运动,所以上面的公式,就变成了,$cos{2{\pi}ft}=\frac{e^{j{2{\pi}ft}}+{e^{-{j{2{\pi}ft}}}}}{2}$,所以,有没有发现,一个余弦信号,其实就是两个共轭向量的叠加。 好像这里又回到了故事最初的起点了,是的,在复数域里,还是满足不管你想要什么,就要不断为之努力。所以,不管什么信号,它在任意时刻都是$x'(t)=x(t)e^{2{\pi}(-f)tj}=x(t)e^{-2{\pi}jft}$这样的,对其求积分$x(f)=\int_{-\infty}^{\infty}{x'(t)}dt=\int_{-\infty}^{\infty}{{x(t)}e^{-2{\pi}jft}}dt$。 这不就是傅立叶变换吗?是的,这就是复数域的傅立叶变换。 Z变换是什么? Z是复平面里的变量,其构成一个复平面(亦称为S平面)所在的平面称为Z平面。 S平面和Z平面之间的关系? 整篇文章没有扒小拉,虽然她是三大变换中年龄最大的,但我感觉小傅和小Z通过彼此,看到了更广阔的的世界,他们是同域中人,所以想给他们个特写。即使在时域中,小傅&小拉,而小Z只是在忽明忽暗的交错空间,难以触碰,然沦为,一阵风,一场空。 “当然最后,这个三角关系,因为从时域到频域的自由变换,而变得幸福美满、和谐共生。所以不管是什么关系,将会怎么发展,取决于你思考的角度,谁都代替不了谁,在频域里都是特别的个体,只是我们通常把人生用时间限制,再被约定俗成的很多东西捆绑,造成出场顺序往往决定故事结尾。帕斯维尔定理说,时域的总能量和频域的总能量是相等的。所以,从频域看,找到独一无二的自己之后,对或错好像也没那么重要了。有些事,只要想做了,结局无非是成了所爱的那道光或是他的影,而两者,我皆愿承受。” 时域到频域的变化有什么用? 作为一大三小白,我只知道经常用来滤波。 以我用MATLAB合成许嵩的《素颜》为例:是素颜吗?也许是,我一开始也没听出来,然后强行脑补才感觉有些神似。 部分时域: 部分频域: 这里在编程中就是采用傅立叶分析进行了滤波,所以没有啪啦啪啦的噪声,虽然和原曲速度有差,我也尝试根据理论数据修改采样频率,最终还是没能调成一致,有感兴趣的可一起交流。 致最可爱的人 感谢邢静老师的指导!感谢奥特曼超人! THE END!
fork()函数类 (1)解析: fork()函数的返回值,若成功调用一次则返回两个值,子进程返回0,父进程返回子进程标记;否则,出错返回-1。 假设程序正确运行并创建子进程成功:子进程中pid得到返回值为0,父进程中pid得到返回值为子进程号,父进程执行一次输出,子进程执行一次输出。 故输出两行Hello World。 (2)解析: fork()函数的返回值,若成功调用一次则返回两个值,子进程返回0,父进程返回子进程标记;否则,出错返回-1。 假设程序正确运行并创建子进程成功:子进程得到返回值为0,父进程得到返回值为子进程号,父进程执行一次输出,子进程执行一次输出,加上fork()函数前面的语句,输出一行Hello World。 故输出三行Hello World。 (3)解析: fork()函数的返回值,若成功调用一次则返回两个值,子进程返回0,父进程返回子进程标记;否则,出错返回-1。 假设程序正确运行,创建一个子进程得到返回值为0,输出 I am the child process,my process ID is 3744 ;父进程得到返回值为子进程号,父进程执行一次输出 I am the parent process,my process ID is 3987 。 故改程序正确运行后的结果是 I am the child process,my process ID is 3744I am the parent process,my process ID is 3987 缺页中断类 (1)解析: 缺页中断次数=页框数 × 页面置换次数。 由程序可知,每次内层循环遍历了100个整形变量,所以页框数=$\frac{100}{50}$ = 2;外层循环有50次,所以页面置换次数为50。 缺页中断次数 = 2 × 50 =100次。 会产生100次缺页中断。 (2)解析: 最佳页面置换法的原则:保留最近重复访问的页面,将以后都不再访问或者很长时间内不再访问的页面调出。 根据题中所给的进程访问序列,可可得到以下置换图: 故缺页次数为7。 页面置换算法类 (1)解析: LRU置换算法的规则:将最近最久未被访问的页面置换出去。 由题意可得: 显而易见,共缺页11次,所以缺页率为11/15≈73%。 故该进程的缺页率为73%。 进程内存分配类 (1)解析: 由题意可得,内存空闲区有: 由分配后的内存情况: 可知,此方法首先使用了满足条件的最大空闲区,这是最差适配的特点。 故此为最差适配。 (2)解析: 由题意可得,内存空闲区有: 由分配后的内存情况: 可知,此方法首先使用了满足条件的最小空闲区,这是最佳适配的特点。 故此为最佳适配。 (3)解析: 由题意可得,内存空闲区有: 由分配后的内存情况: 可知,此方法首先使用了满足条件的低地址的空闲区,这是首次适配的特点。 故此为首次适配。 (4)解析: 由题意可得,内存空闲区有: 由分配后的内存情况: 可知,此方法并没有分配任何空闲区,这是下次适配的特点。 故此为下次适配。 UNIX系统中文件权限类 (1)解析: UNIX系统中,文件权限规则:A1A2A3,A1代表文件属主,A2代表同组用户,A3代表其他用户。其中A=a×4+b×2+c,若a=1,则为可读,b=1,则为可写,c=1,则为可执行。 由题意可知,A1为7=1×4+1×2+1,则a=b=c=1,所以,文件属主可读、可写、可执行File1;A2为5=1×4+0×2+1,则a=c=1,所以,同组用户可读、可执行;A3为5=1×4+0×2+1,则a=c=1,所以,其他用户可读、可执行。 故文件属主可执行File1,文件属主可读File1,同组用户可执行File1,其他用户可读File1。 银行家算法类 (1)解析: 安全序列是指对当前申请资源的进程排出一个序列,保证按照这个序列分配资源完成进程。我们假设有进程P1,P2,.....Pn,则安全序列要求满足:Pi(1<=i<=n)需要资源<=剩余资源 + 分配给Pj(1 <= j < i)资源。 解题思路:首先根据系统状态列出各进程需要的资源;然后根据当前系统剩余资源,找到一个需要资源不大于剩余资源的进程,此时,系统剩余资源就是可用资源;然后此进程的已分配资源加上可用资源,为新的可用资源,并继续与下一个进程的需要资源比较,以此类推写出安全序列。 由于安全序列的不唯一性,针对做题来说,还是根据选项去反推本序列是否安全更合适。 如: 当前系统剩余资源(2,3,3)A,P3需要(2,1,1)<(2,3,3)满足,则可用资源变为(4,4,7);P1需要(0,0,6)<(4,4,7)满足,则可用资源变为(8,4,12);P4需要(3,4,7)<(8,4,12)满足,则可用资源变为(10,5,14);P2需要(1,3,4)<(10,5,14)满足,则可用资源变为(14,5,16);P5需要(1,1,1)<(14,5,16)满足,则可用资源变为(15,6,17)。 故P3,P1,P4,P2,P5。 重组存储器类 (1)解析: 0BFFFFH-0A0000H=1FFFFH=131071;131071÷(16×1024)=7。 故应使用8片。 8259A级联类 (1)解析: 8259A的IR0~IR7用来接收外设的中断信号,1片最多可以有8级中断;芯片级联时,需要留出一个口接con从片,所以9片芯片级联后有只有最后一片是8个口接收中断信号,其他8片都是7个口,所以8+8×7=64级。 故可以使CPU的kepingbizh可屏蔽中断最多扩展到64级。 8259A类 (1)解析: ICW2是设置中断类型码的初始化命令字,其高5位设置中断类型码,低3位自动插入IR的编码。 由题意可知, ICW2 = 83H = 10000011B,所以 IR2 的中断类型码为10000, 低3位编码为010,即中断类型码为10000010B = 82H。 故8259A发给CPU的中断类型码是82H。 8255A类 (1)解析: 8255A方式控制字: 由题意可得:D7=1; D6D5=00;D4=0;D3D2D1D0=xxxx;即控制字为1000xxxx B=8xH。 故控制字应该设置为80H/81H/88H。 (2)解析: 8255A口C按位置位/复位控制字 由题意可知,端口B工作在方式1,且用$ INRT_B $向外发出中断,所以PC2口置1,即D3D2D1=010,又因为端口B作为输入,所以C口置1,即D0=1。 故正确的置位/复位控制字为05H。 8253类 (1)解析: 8253的控制字: 由计数器1可得:D7D6=01;由计数值266,且计数器1是16位计数器,所以:D5D4=11; 由工作在模式3可得:D3D2D1=x10;D0=x;即控制字为0111x10x B,所以可能为76H/7EH。 故控制字应该设置为76H/7EH。 (2)解析: 8252工作在模式2时是作为速率波发生器使用,计数器在减“1”计数过程中,GATE变为无效(输入0电平),则暂停减“1”计数,待GATE恢复有效后,从初值n开始重新计数。 由题意可知,时钟速率为20KHz,要想保证没10ms发出一个信号,则计数值应为20KHz×10ms=200。 故正确的计数值是200。 8251A类 解析: 8251A的异步方式控制字: 由一位停止位可得:D7D6=01;由奇校验可得:D5D4=01; 由字符长度为8位可得:D3D2=11;由16分频可得:D1D0=10;即控制字为01011110B。 故应向其模式控制寄存器写入5EH。 调度类 (1)解析: SCAN调度算法的规则:比磁头大的序列升序访问,比磁头小的序列降序访问。 比磁头大的序列升序排序:110,170,180,195;比磁头小的序列降序排序:68,45,35,12。 故采用SCAN算法得到的磁道访问序列是:110,170,180,195,68,45,35,12。 (2)解析: SSF调度算法的规则:先请求离磁头最近的磁道的访问,然后就近访问,以此类推。 故采用SSF算法得到的磁道访问序列是:110,68,45,35,12,170,180,195。 (3)解析: FCFS调度算法的规则:按照访问请求次序为各进程服务。 故采用FCFS算法得到的磁道访问序列是:35,45,12,68,110,180,170,195。 其他 (1)解析: 信号量,可以被一个线程释放,另一个线程获取,多线程同步。mutex,用于线程互斥,其对象值只能为0和1~值0,表示锁定状态,当前对象被锁定,用户线程或进程如果试图Lock临界资源,则进入排队等待;值1,表示空闲状态,当前对象为空闲,用户线程或进程可以Lock临界资源,之后mutex值减1变为0。 mutex的初值为1,说明同时只允许一个进程进入临界区,则有一个进程在临界区; k个进程在等待队列中,则有k个进程在等待区; 所以一共有1+k个进程,每个进程都访问mutex时,mutex的值都减1,即,此时mutex的值为1-(1+k)=-k; 故信号量的值为-K。 (2)解析: 页面数=$frac{页表内存}{页面大小}$;页表内存=页表项个数 × 物理页号; 页表项个数=$frac{虚拟地址空间}{页面大小}$(计算过程注意单位统一) 代入数据:页表项个数=$\frac{2*1024*1024}{4}$ 个; 页表内存=$\frac{2*1024*1024}{4}$ &times; 4 B; 页面数=$\frac{2*1024*1024}{4*(4*1024)}$ &times; 4 = 512 个。 故页表需要占用512个页面。 (3)解析: 没有成组操作时,块使用率=$frac{块使用大小}{块大小}$ × 100%。 每个逻辑记录为80个字符,所以块使用大小为80;每个块大小为1024个字符。 即没有成组操作时,块使用率= $\frac{80}{1024}$ × 100% ≈ 8% 。 故磁盘的空间利用率是 8% 。 (4)解析: 成组操作时,快使用率=$frac{块使用大小×块因子}{块大小}$ × 100%。 每个逻辑记录为80个字符,所以块使用大小为80;每个块大小为1024个字符,块因子为12。 即成组操作时,块使用率= $frac{80×12}{1024}$ × 100% ≈ 94% 。 故磁盘的空间利用率是 94% 。 (5)解析: 每个进程可申请资源数=$frac{总资源数}{总进程数}$。 由题意可得,$frac{总资源数}{总进程数}$ = $\frac{7}{3}$=2……1,所以有两个进程可以获取2个资源,一个进程获取3个资源。 故每个进程最多可以申请的资源个数是3。 (6)解析: 总线带宽=总线频率×总线宽度(注意单位) 代入数据可得,总线宽度=66MHZ × $\frac{32}{4}$ B =264MBps。 故总线的带宽为264MBps。 (7)解析: 在分页式存储管理方案的系统中,页数 = $frac{逻辑地址}{内存块大小}$ 。 由题意可得,页数 = $\frac{ 2^{32} }{2^{10} }$ 。 故用户程序最多可划分成 $2^{22}$。 (8)解析: 前10个索引项直接存放文件信息的物理块号,直接索引,最多寻址10个物理块;第11项指向一个物理块,该块中最多可放100个文件物理块的块号,第一次间接索引;第12个索引项是第二次间接索引,最多可寻址100100个物理块。所以,总物理块数为:10+100+100100=10110。 故一个文件最多为10110块。 (9)解析: 启动1次磁盘,直接索引1~10物理块;启动2次磁盘,一级索引11~110物理块;启动3次磁盘,二级索引111~10110物理块。所以要访问第1000块时,找到主索引后,需要启动磁盘3次。 (10)解析: 二次重叠控制方式的指令执行方式: 假设取指令、分析指令和执行指令的时间都相等,每段的时间都为t,执行一条指令的时间T=$t_取指令$+$t_分析指令$+$t_执行指令$。如果我们把取第k+1条指令所用的时间,提前到与分析第k条指令同时进行,那么分析第k+1条指令会与执行第k条指令同时进行,则执行n条指令所用的时间是:T=3×t+(n-1)×t。 故所需执行的时间为:T=3×t+(n-1)×t。 (11)解析: 在计算机中,浮点数只用阶码和尾数表示:。 浮点数的范围由阶码的位数决定,精度由尾数决定。 由题意可知阶码是用补码表示的,且共四位,其中一位是阶符,所以阶码的最大值是7,所以由此表示的最大正数是$2^7$-1。 故规格化浮点数所能表示的最大整数是$2^7$-1。 (12)解析: 对一级页表而言,查页表项的平均时间 = 快表查找时间 × 命中率 + 访问内存的时间 × (1-命中率)+1×访问内存的时间。 由题意可得:查页表项的平均时间 = 0 +0.4us*(1-90%)+1×0.4us= 0.44us。 故有效访问时间是0.44us。 (13)解析: $2^{地址线条数}$= 存储容量(直接寻址能力)。 由题意可得,$2^{地址线条数}$= 64GB =$2^6$ × $2^{30}$ = $2^{36}$。 故该处理器的地址线有36条。 (14)解析: 由题意可知,VALB=30=1EH,所以(VALB AND 0FH) OR (VALB XOR 0FH)=(1EH & 0FH)|(1EH ⊕ 0FH)=1FH。 故表达式(VALB AND 0FH) OR (VALB XOR 0FH)的值为1FH。 (15)解析: 在调度的过程中的,内存的变化如下: 标红1号区,内存为320-224=96M;标红2号区,内存为224-120=104M; 标红3号区,内存为1024-128-320-224-288=64M;显然1号空闲区内存最大。 故系统中剩余的最大空闲分区是104M。 (16)解析: 由题意可得: 故存放数据07H的物理地址是200FEH。 (17)解析: 由题意可得,共8个盘面,每个盘面有2500×80=200000个扇区。 逻辑号为385961,385961/200000≈1.929805,则在第2个盘面上,盘面号为1。 (385961 mod 200000)/80≈2324.5125,则在第2325个柱面上,柱面号为2324。 (385961 mod 200000)mod 80≈41,则在第41个扇区上,扇区号为40。 故该数据块对应的盘面、柱面和扇区号各为1,2324,40。 (18)解析: 在UNIX三级索引结构中,0-9项为直接索引,访问时共10个数据块;第10项为一级间接索引,访问时共$2^{10}$个数据块;第11项为二级间接索引,访问时共$2^{10}$×$2^{10}$个数据块;第12项为三级间接索引,访问时共$2^{10}$×$2^{10}$×$2^{10}$个数据块。 所以共有10+$2^{10}$+$2^{20}$+$2^{30}$个数据块,又因为磁盘块大小为4096B。 故该文件系统中文件的最大尺寸不能超过(10+$2^{10}$+$2^{20}$+$2^{30}$)×4096B。 (19)解析: 首先计算出每个磁盘块有文件控制块512/64=8,有256个文件控制块时,表明有256/8=32个磁盘块。 在第一个磁盘块需要访问磁盘一次,在第二个磁盘块需要访问磁盘块两次,依次类推,所以平均有(1+2+3+...+32)÷32=33÷2=16.5次。 故查找该目录文件的某一个文件控制块的平均访盘次数是16.5。 另附:一般情况下的分析。若目录文件分解前占用n个磁盘块,分解后用m个磁盘块存放文件名和文件内部号,则推导出二者的表达式: 分解前,平均访问磁盘次数:(1+2+...+n)÷n=(n+1)2(1+2+...+n)÷n=(n+1)/2 ;分解后,平均访问磁盘次数:(2+3+...+(m+1))÷m=(m+3)/2。 (20)解析: 异步通信的数据格式如下: 由题意可得,起始位:0; 5位数据位发送13H:10011;偶校验:1(13H有奇数个1,所以补1);停止位:1; 又因为发送数据时,从低位开始发送,所以数据帧格式为11100110。 故发送数据13H到传输线上的信息为E6H。 END!
分支 先例 写一个程序,按百分制评等级:[90,100]等级为A,[80,90)等级为B,[60,80)等级为C,[0,60)等级为D,当用户输入分数时,自动转换为ABCD的形式输出。 rank1.py >>> score = int ( input ('Please Input the Score:')) if score < 0 or score > 100: print ('Input Error!') if 90 <= score <= 100: print ('A') if 80 < score <90: print ('B') if 60 < score <=80: print ('C') if 0 <= score <=60: print ('D') F5运行后,输入分数: rank2.py >>> score = int ( input ('Please Input the Score:')) if score < 0 or score > 100: print ('Input Error!') elif 90 <= score <= 100: print ('A') elif 80 < score <90: print ('B') elif 60 < score <=80: print ('C') elif 0 <= score <=60: print ('D') F5运行后,输入分数: rank3.py >>> score = int ( input ('Please Input the Score:')) if score < 0 or score > 100: print ('Input Error!') else: if 90 <= score <= 100: print ('A') else: if 80 < score <90: print ('B') else: if 60 < score <=80: print ('C') else: print ('D') F5运行后,输入分数: rank1 VS rank2 VS rank3 rank1的特点:不论程序执行到哪一步能满足条件,都会把整个程序都走一遍,再输出结果。 rank2的特点:只要程序执行到满足条件的那一步,就会终止程序输出结果,比rank1节省时间。 rank3的特点:与rank2的执行方式一样,只是运用了python中特有的elif语句,简洁明了!rank2体现了python中的缩进机制,完美的避开了,在其他语言中经常会掉的坑。 悬挂else 像C语言中有如下代码: if (a > 0) if (b > 0) printf("^_^") else printf("&-&"); 请问else是和哪个if搭配的呢?对和第二个if搭配!BUT,在大量代码面前,这种框架的关键字像沧海一粟,找起来很费劲。所以,悬挂else的问题在python中完全不存在。 条件表达式(三元操作符) 买家秀: x,y = 1,2 if x < y: print('min =',x) else: print('min =',y) F5运行后得: 卖家秀: x,y =1,2 print('min =', x if x < y else y) F5运行后得:即使得到相同的结果,过程仍可能有很大的差别!由上述对比可知,条件表达式的语法为: x if 条件 else y 当条件为真时,程序将返回x的值,反之,返回y的值。 断言(assert) >>> assert 1 > 2 Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> assert 1 > 2 AssertionError 由此异常可知,关键字 assert 后的条件为假时程序便会产生AssertionError,所以说,当我们需要确保程序中的某一个条件一定为真才能让程序正常工作的话时,用assert在程序中置入检查点。 循环 while 循环 while 条件: 循环体 只要条件为真,程序就会一直执行循环体。 while 1: str1=str(input("你现在有什么想法:")) print("原来你很",str1,"呀!") for 循环 for 目标 in 表达式: 循环体 目标是指变量,表达式可为序列,可以是列表也可以是字符串。 >>> players = ['网易云音乐','酷狗音乐','QQ音乐'] >>> for player in players: print ('安装:',player,len(player)) 安装: 网易云音乐 5 安装: 酷狗音乐 4 安装: QQ音乐 4 for 与很多BIF连用时会实现各种各样的功能,这里以range([star,]stop[,step=1])为例: >>> for i in range(1,10,2): print(i) 1 3 5 7 break和continue 关键字break的作用是终止当前循环,跳出循环体。 >>> for i in '123456789': if i == '7': break print(i) 1 2 3 4 5 6 关键字continue的作用是终止当前循环,开始下次循环。 >>> for i in '123456789': if i == '7': continue print(i) 1 2 3 4 5 6 8 9 需要注意,循环语句可以有 else 子句,它在穷尽列表(以for循环)或条件变为 false (以while循环)导致循环终止时被执行,但循环被break终止时不执行。 >>> for i in range(1,10): for x in range(2,i): if i % x == 0: print(i,'能分解成',x,'*',i//x) break else: print(i,'是质数!') 1 是质数! 2 是质数! 3 是质数! 4 能分解成 2 * 2 5 是质数! 6 能分解成 2 * 3 7 是质数! 8 能分解成 2 * 4 9 能分解成 3 * 3 END!
1.字典 访问字典里的参数 >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> dict1['music'] KeyError: 'music' 这里报错是因为,字典中并没有key值为 'music',为了避免 KeyError 发生,有两个办法: 先用 in 操作符判断一下 key 是否存在: >>> 'music' in dict1 False 用 get() 方法,在Key不存在的时候,返回None: >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> print (dict1.get('music')) None 修改字典 >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> dict1['singer']='kesha' >>> dict1['song']='Rainbow' >>> dict1 {'singer': 'kesha', 'sex': 'female', 'song': 'Rainbow'} 删除字典元素 >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> del dict1['sex'] #删除键是'sex'的条目 >>> dict1 {'singer': 'GEM', 'song': '查克靠近'} >>> dict1.clear() # 清空词典中所有条目 >>> dict1 {} >>> del dict1 # 删除词典 >>> dict1 NameError: name 'dict1' is not defined 字典的BIF 比较字典大小:operator() >>> import operator #首先要导入运算符模块 >>> operator.gt(dict1,dict2) #意思是greater than(大于) False >>> operator.ge(dict1,dict2) #意思是greater and equal(大于等于) True >>> operator.eq(dict1,dict2) #意思是equal(等于) True >>> operator.le(dict1,dict2) #意思是less and equal(小于等于) True >>> operator.lt(dict1,dict2) #意思是less than(小于) False 字典的内置方法 浅拷贝字典,注和直接赋值不同:copy() >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> dict2=dict1 >>> dict3=dict1.copy() >>> dict1['singer']='kesha' >>> dict1['song']='Rainbow' >>> dict1 #dict1改变 {'singer': 'kesha', 'sex': 'female', 'song': 'Rainbow'} >>> dict2 #直接赋值得到的dict2跟着改变 {'singer': 'kesha', 'sex': 'female', 'song': 'Rainbow'} >>> dict3 #浅拷贝得到的dict3保持不变 {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} 创建一个新字典,以序列seq中元素做字典的键,字典所有键对应的初始值为value:fromkeys(seq[, value]) >>> seq = ('singer', 'sex', 'song') >>> dict1 = dict.fromkeys(seq) >>> dict1 {'singer': None, 'sex': None, 'song': None} >>> dict2 = dict.fromkeys(seq,2) >>> dict2 {'singer': 2, 'sex': 2, 'song': 2} -以列表返回可遍历的(键, 值) 元组数组:items() >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> dict1.items() dict_items([('singer', 'GEM'), ('sex', 'female'), ('song', '查克靠近')]) 把字典dict2的键值对更新到dict里:update(dict2) >>> dict1= {'singer': 'GEM', 'sex': 'female'} >>> dict2= {'song': '查克靠近'} >>> dict1.update(dict2) >>> dict1 {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} 以列表返回字典中的所有值:values() >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> list(dict1.values()) ['GEM', 'female', '查克靠近'] 删除字典给定键 key 所对应的值,返回值为被删除的值:pop(key[,default]) >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> pop1=dict1.pop('singer') >>> pop1 'GEM' 随机返回并删除字典中的一对键和值(一般删除末尾对):popitem() >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> pop1=dict1.popitem() >>> pop1 ('song', '查克靠近') >>> dict1 {'singer': 'GEM', 'sex': 'female'} 任何情况下都可以使用此种方法吗? >>> dict2={} >>> pop2=dict2.popitem() KeyError: 'popitem(): dictionary is empty' 上例说明,如果字典已经为空,调用此方法,就发生Error。 2.集合 set的内部结构和dict很像,唯一区别是不存储value,也就是说当用花括号括起来一堆没有映射关系的元素时就创建了一个集合。 访问集合里的参数 和字典一样,我们可以先判断要访问的参数是否在集合内: >>> set1= {'酷狗音乐', '网易云音乐', '虾米音乐'} >>> 'QQ音乐' in set1 False 更新集合 用add()添加元素,注意如果添加的元素已经存在于set中,add()不会报错,但是不会加进去了。 >>> set1= {'酷狗音乐', '网易云音乐', '虾米音乐'} >>> set1.add('QQ音乐') >>> set1 {'QQ音乐', '酷狗音乐', '网易云音乐', '虾米音乐'} 用remove()删除元素,注意如果删除的元素不存在set中,会出现Error: >>> set1= {'酷狗音乐', '网易云音乐', '虾米音乐'} >>> set1.remove('QQ音乐') KeyError: 'QQ音乐' 集合的内置方法 以下方法应用都比较简单,而且很多前面都已经提到过,所以就不在一一举例。 END!
1.列表 向列表中添加元素 一次只能添加一个元素到列表末尾:append() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> player.append('落网') >>> player ['酷狗音乐', '网易云音乐', 'QQ音乐', '虾米音乐', '落网'] 一次添加多个元素到列表末尾:extend([]) >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> player.extend(['落网','酷我音乐']) >>> player ['酷狗音乐', '网易云音乐', 'QQ音乐', '虾米音乐', '落网', '落网', '酷我音乐'] 插入元素,可指定元素位置:insert() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> player.insert(0,'落网') >>> player ['落网', '酷狗音乐', '网易云音乐', 'QQ音乐', '虾米音乐'] 从列表中获取元素 >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> temp=player[0] >>> temp '酷狗音乐' >>> player[0]=player[1] >>> player ['网易云音乐', '网易云音乐', 'QQ音乐', '虾米音乐'] >>> player[1]=temp >>> player ['网易云音乐', '酷狗音乐', 'QQ音乐', '虾米音乐'] 从列表删除元素 remove() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> player.remove('QQ音乐') >>> player ['酷狗音乐', '网易云音乐', '虾米音乐'] del() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> del player[2] >>> player ['酷狗音乐', '网易云音乐', '虾米音乐'] >>> del player >>> player NameError: name 'player' is not defined pop() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> er=player.pop() >>> er '虾米音乐' >>> player ['酷狗音乐', '网易云音乐', 'QQ音乐'] 列表分片[:] 列表分片 >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> player[1:3] ['网易云音乐', 'QQ音乐'] >>> player ['酷狗音乐', '网易云音乐', 'QQ音乐', '虾米音乐'] 列表拷贝 >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> player1=player[:] >>> player1 ['酷狗音乐', '网易云音乐', 'QQ音乐', '虾米音乐'] 列表中常用的操作符 比较运算符 >>> number1=[3,4,2,6] >>> number2=[3,4,6,6] >>> number1>number2 False 列表中,从第0个元素开始依次向后比较,只要不相等,不再继续向后比较。 逻辑操作符 >>> number1=[3,4,2,6] >>> number2=[3,4,6,6] >>> number3=[3,2,6,4] >>> (number1<number2)or(number1==number3) True 连接操作符 >>> number1=[3,4,2,6] >>> number2=[3,4,6,6] >>> number1+number2 [3, 4, 2, 6, 3, 4, 6, 6] 重复操作符 >>> number1=[3,4,2,6] >>> number1*3 [3, 4, 2, 6, 3, 4, 2, 6, 3, 4, 2, 6] >>> number1 #number1没有改变 [3, 4, 2, 6] >>> number1*=3 >>> number1 #number1改变 [3, 4, 2, 6, 3, 4, 2, 6, 3, 4, 2, 6] 成员关系操作符(in、not in) >>> number1=[3,4,2,6,[7,8,9]] >>> 3 in number1 True >>> 7 not in number1 #由结果可知成员关系操作符不能识别列表中的列表元素 True >>> number1[4][0] #想访问列表中的列表元素,类似二维数组 7 列表的BIF 可以在编译器内查看列表有哪些BIF 检测参数在列表中出现的次数:count([parameter]) >>> number1=[3, 4, 2, 6, 3, 4, 2, 6, 3, 4, 2, 6] >>> number1.count(3) 3 返回参数在列表中的位置:index([parameter],[start],[end]) >>> number1=[3, 4, 2, 6, 3, 4, 2, 6, 3, 4, 2, 6] >>> number1.index(3,2,6) #从第2个参数到第六个参数之间的范围内查找参数3的位置 4 将整个列表原地翻转:reverse() >>> number1=[3, 4, 2, 6, 3, 4, 2, 6, 3, 4, 2, 6] >>> number1.reverse() >>> number1 [6, 2, 4, 3, 6, 2, 4, 3, 6, 2, 4, 3] 将列表内元素排序,用func设置排序算法,key表示与算法搭配的关键字:sort(func,key,reverse = Flase) >>> number1=[3, 4, 2, 6, 3, 4, 2, 6, 3, 4, 2, 6] >>> number1.sort() #默认是从小到大排序 >>> number1 [2, 2, 2, 3, 3, 3, 4, 4, 4, 6, 6, 6] >>>number1=[3, 4, 2, 6, 3, 4, 2, 6, 3, 4, 2, 6] >>> number1.sort(reverse = True) #从大到小排序 >>> number1 [6, 6, 6, 4, 4, 4, 3, 3, 3, 2, 2, 2] >>> number1=[3,2,6,4] >>> number2=number1[:] #通过分片的方法获得一个和number1相同的列表 >>> number3=number1 #通过直接赋值的方法获得一个和number1相同的列表 >>> number2 [3, 2, 6, 4] >>> number3 [3, 2, 6, 4] >>> number1.sort() #将number1排序 >>> number1 #number1改变 [2, 3, 4, 6] >>> number2 #number2改变 [3, 2, 6, 4] >>> number3 #number3不变 [2, 3, 4, 6] 这说明通过分片拷贝获得的新列表是不受原列表影响的独立列表,而通过赋值获得的只是改变了列表名称,本质上还是同一个列表。 2.元祖 向元祖中插入元素 >>> tuple1=('酷狗音乐', '网易云音乐', 'QQ音乐', '虾米音乐') >>> tuple1=tuple1[:2]+('落网',)+tuple1[2:] >>> tuple1 ('酷狗音乐', '网易云音乐', '落网', 'QQ音乐', '虾米音乐') 从元祖中获取元素 >>> tuple1=(1,2,3,4) >>> tuple2=tuple1[:2] >>> tuple2 (1, 2) 删除元祖 >>> tuple1=('酷狗音乐', '网易云音乐', 'QQ音乐', '虾米音乐') >>> del tuple1 >>> tuple1 NameError: name 'tuple1' is not defined 元祖可变?不可变? >>> tuple1= ('酷狗音乐', '网易云音乐', ['华晨宇', '丁可']) >>> list1= tuple1[2] >>> list1[0] = '杨千嬅' >>> list1[1] = '莫文蔚' >>> tuple1 ('酷狗音乐', '网易云音乐', ['杨千嬅', '莫文蔚']) 这说明tuple所谓的“不变”是说,tuple的每个元素的指向不变。 元祖拷贝和操作符的用法与列表类似 3.字符串、列表和元祖的关系 序列的特点 都可以通过索引得到每一个元素; 默认索引值总是从0开始; 可以通过切片的方法得到一个范围内的元素的集合; 有很多共同的操作符(重复操作符、拼接操作符、成员关系操作符)。 序列的BIF 返回sub的长度:len(sub) >>> tuple1= ('酷狗音乐', '网易云音乐', ['华晨宇', '丁可']) >>> len(tuple1) 3 返回序列中的最大值、最小值,对于字母是比较它们的ASCII码:max(seq)、min(seq)在数学类函数中介绍的max()和min(),只说明了它们对数字的处理能力,其实它们也可以对序列操作。 >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> max(player) '虾米音乐' >>> min(player) 'QQ音乐' 对序列元素进行翻转:reversed() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> reversed(player) #这样返回的是一个可迭代对象 <list_reverseiterator object at 0x0000000002E09780> >>> list(reversed(player)) #这才是翻转的正确操作 ['虾米音乐', 'QQ音乐', '网易云音乐', '酷狗音乐'] 生成每个元素的索引值和iterable值和组成的元祖的列表:enumerate() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> enumerate(player) <enumerate object at 0x00000000030D71F8> >>> list(enumerate(player)) [(0, '酷狗音乐'), (1, '网易云音乐'), (2, 'QQ音乐'), (3, '虾米音乐')] 返回由各个参数的序列组成的元祖:zip() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> singer=['华晨宇','丁可','杨乃文','王若琳'] >>> zip(player,singer) <zip object at 0x00000000030DF348> >>> list(zip(player,singer)) [('酷狗音乐', '华晨宇'), ('网易云音乐', '丁可'), ('QQ音乐', '杨乃文'), ('虾米音乐', '王若琳')] 对序列元素进行排序:sorted() >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> sorted(player) ['QQ音乐', '网易云音乐', '虾米音乐', '酷狗音乐'] 返回序列中数值设定参数start的总和: sum(iterable[,start=0]) >>> tuple1=(1,2,3,4,) >>> sum(tuple1) 10 >>> sum(tuple1,5) 15 任何参数都能用sum()吗? >>> tuple1=('a','b','c','d') >>> sum(tuple1) TypeError: unsupported operand type(s) for +: 'int' and 'str' 当序列的元素有非数字类型时报错了,说明sum()只能对数字型数据进行操作。 END!
1.字符串中使用引号 非成对出现的引号,用转义字符"\": >>> str1='Where\'re you now?' >>> print(str1) Where're you now? 成对出现的引号:1)单引号中可用双引号 >>> str2='"DJY"' >>> print(str2) "DJY" 2)双引号中可用单引号 >>> str3="'DJY'" >>> print(str3) 'DJY' 3)三引号可保持字符串原来的格式(从转义字符中被解救的感觉) >>> str4='''DJY FXW''' >>> print(str4) DJY FXW >>> str5="""DJY FXW""" >>> print(str5) DJY FXW 如果想在字符串中既有成对单引号又有成对双引号: >>> str61="'djy'" >>> str62='"fxw"' >>> print(str61+str62) 'djy'"fxw" 2.字符串中显示转义字符 如果想在字符串中显示少量转义字符"\": >>> str1='DJY\\FXW' >>> print(str1) DJY\FXW 此种方法常用在:发出系统响铃声 \a,退格符 \b,换行符 \n,横向制表符(TAB) \t,纵向制表符 \v,回车符 \r,换页符 \f,八进制数代表的字符 \o,十六进制数代表的字符 \x,其它的字符以普通格式输出 \other空字符 \0,反斜杠 \。 如果想在字符串中显示大量转义字符"\": >>> str2=r'C:\DJY\djy\d\j\y' #r是来自于原始字符串(raw strings) >>> print(str2) C:\DJY\djy\d\j\y 若还想以结尾,只需改为: >>> str2=r'C:\DJY\djy\d\j\y\\' >>> print(str2) C:\DJY\djy\d\j\y\ 3.字符串运算符 字符索引[] >>> str1='python2048' >>> str1[6] ‘2’ >>> str1[-1] '8' 字符串分片[:] >>> str1='python2048' >>> str1[6:10] '2048' >>> str1[:6] 'python' 字符串连接+ >>> str1='python' >>> str2='2048' >>> str1+str2 'python2048' 字符串重复* >>> str1='python2048' >>> str1*3 'python2048python2048python2048' 4.字符串格式化 字符串格式化符号 格式化字符及其ASCII码:%c >>> '%c %c %c'%(97,98,99) 'a b c' 格式化字符串:%s >>> '%s'%'djy' 'djy' 格式化整数:%d >>> '%d+%d=%d'%(1,2,1+2) '1+2=3' 格式化无符号八进制、十六进制数(小写、大写):%o、%x、%X >>> '%X'%(10) 'A' 格式化定点数,可设置小数点后的精度:%f >>> '%f'%99.09584 '99.095840' 用科学计数法格式化定点数(小写、大写):%e、%E >>> '%e'%99.09584 '9.909584e+01' 根据值的大小决定使用%f还是%e(%E):%g、%G >>> '%G'%99.09584 '99.0958' 格式化操作符辅助指令 显示最小总宽度m,小数点后的位数n:m.n >>> '%9.2f'%99.09584 ' 99.10' 左对齐:- >>> '%-20f'%2 '2.000000 ' 在正数前面显示加号(+):+ >>> '%+f'%2 '+2.000000' 在八进制数前面显示零('0'),在十六进制数前面显示'0x'或'0X' >>> '%#o'%10 '0o12' 显示的数字前面填充'0'取代空格:0 >>> '%020f'%10 '0000000000010.000000' 5.字符串的BIF 把字符串的第一个字符改成大写:capitalize() >>> str1='python精英群' >>> str1.capitalize() 'Python精英群' 把整个字符串的所有字符改为小写:casefold() >>> str2='PYTHON2048' >>> str2.casefold() 'python2048' 将字符串居中,并用空格填充至长度width形成新字符串:center(width) >>> str3='python2048' >>> str3.center(20) ' python2048 ' 返回sub在字符串里出现的次数,start和end参数表示范围:count(sub[,start[,end]]) >>> str4='djydjydjy' >>> str4.count('jy',2,9) 2 检查字符串是否以sub子字符串结束,如果是返回True,否则返回False:endswith(sub[,start[,end]]) >>> str5='djydjydjy' >>> str5.endswith('jy',2,9) True 把字符串中的tab符号(t)转换为空格,如不指定参数,默认空格数tabsize=8:expandtabs([tabsize=8]) >>> str6='djy\tpython\tfxw' >>> str6.expandtabs() 'djy python fxw' 检测sub是否包含在字符串中,如果有则返回索引值,否则返回-1:find(sub[,start[,end]]) >>> str7='djyfxw' >>> str7.find('c') -1 检测sub是否包含在字符串中,如果有则返回索引值,否则会出现Error:index(sub[,start[,end]]) >>> str8='djyfxw' >>> str8.index('c') #发生Error ValueError: substring not found 如果字符串中所有字符都为字母或数字,则返回True,否则返回False:isalnum() >>> str9='djy&fxw' >>> str9.isalnum() False 如果字符串中字符都为字母,则返回True,否则返回False:isalpha() >>> str10='djy&fxw' >>> str10.isalpha() False 如果字符串为Unicode数字、全角数字(双字节)则返回True,罗马数字、汉字数字返回Flase, byte数字(单字节)会出现Error:isdecimal() >>> str11='2048' >>> str11.isdecimal() True 如果字符串为Unicode数字、byte数字(单字节)、全角数字(双字节)、罗马数字则返回True, 汉字数字返回Flase:isdigit() >>> str12='2048' >>> str12.isdigit() True 如果字符串为Unicode数字、全角数字(双字节)、罗马数字、汉字数字则返回True,byte数字(单字节)会出现Error:isnumeric() >>> str13='2048' >>> str13.isnumeric() True 如果字符串中字符都是小写,则返回True,否则返回Flase:islower() >>> str14='奥特曼超人' >>> str14.islower() False 如果字符串中字符都是大写,则返回True,否则返回Flase:isupper() >>> str15='奥特曼超人' >>> str15.isupper() False 如果字符串只包含空格,则返回True,否则返回Flase:isspace() >>> str16=' ' >>> str16.isspace() True 如果字符串是标题化(所有单词都是以大写开始,其余字母均小写),则返回True,否则返回Flase:istitle() >>> str17='Hello,Djy' >>> str17.istitle() True 以字符串为分隔符,插入到sub中所有的字符之间:join(sub) >>> str18='DJY' >>> str18.join('fxw') 'fDJYxDJYw' 返回一个左对齐的字符串,并用空格填充至长度为width的新字符串:ljust(width) >>> str19='DJY' >>> str19.ljust(20) 'DJY ' 将字符串中所有的大写字母转化为小写:lower() >>> str20='DJY' >>> str20.lower() 'djy' 去掉字符串左边的所有空格:lstrip() >>> str21=' DJY' >>> str21.lstrip() 'DJY' 找到子字符串sub,把字符串分成一个三元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回('原字符串',","):partition(sub) >>> str22='djyandfxw' >>> str22.partition('and') ('djy', 'and', 'fxw') 把字符串中的old子字符串替换成new子字符串,如果指定count 则替换不能超过count次:replace(old,new[,count]) >>> str23='djyandfxw' >>> str23.replace('a','d',1) 'djydndfxw' 从右开始检测sub是否包含在字符串中,如果有则返回索引值,否则返回-1(与find()类似):rfind(sub[,start[,end]]) 从右开始检测sub是否包含在字符串中,如果有则返回索引值,否则会出现Error(与index()类似):rindex(sub[,start[,end]]) 返回一个右对齐的字符串,并用空格填充长度至width的新字符串:rjust(width) >>> str24='djyandfxw' >>> str24.rjust(20) ' djyandfxw' 从右开始找子字符串sub,把字符串分成一个三元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回('原字符串',",")(与partition(sub)类似):rpartition(sub) 删除字符串末尾的所有空格:rstrip() >>> str25='djyandfxw ' >>> str25.rstrip() 'djyandfxw' 不带参数默认是以空格为分隔符切片为字符串,如果有设置maxsplit参数,则仅分割maxsplit个子字符串,返回切片后的子字符串拼接的列表:split(sep=None,maxsplit=-1) >>> str26='djy python 2048 fxw' >>> str26.split() ['djy', 'python', '2048', 'fxw'] 按'n'分隔,返回一个包含各行作为元素的列表,如果指定keepends参数,则返回前keepends行:splitlines(([keepends])) >>> str27='djy\npython\n2048\nfxw' >>> str27.splitlines(2) ['djy\n', 'python\n', '2048\n', 'fxw'] 检查字符串是否以prefix开头,是则返回True,否则返回False:startswith(prefix[,start[,end]]) >>> str28='djywanan' >>> str28.startswith('d') True 删除字符串前边和后边所有的空格,chars参数可以设置删除的字符:strip([chars]) >>> str29='djy wanan' >>> str29.strip('d') 'jy wanan' 翻转字符串中的大小写:swapcase() >>> str30='DJYwanan' >>> str30.swapcase() 'djyWANAN' 返回标题化(所有的单词都是以大写开始,其余字母均为小写)的字符串:title() >>> str31='DJY wanan' >>> str31.title() 'Djy Wanan' 根据table的规则(可以由str.maketrans('a','b')定制)转换字符串中的字符:translate(table) >>> str32='DJYDJYDJY' >>> str32.translate(str.maketrans('DJY','FXW')) 'FXWFXWFXW' 将字符串中所有的小写转化为大写:upper() >>> str33='djywanan' >>> str33.upper() 'DJYWANAN' 返回长度为width的字符串,原字符串右对齐,前面用0填充:zfill(width) >>> str34='djywanan' >>> str34.zfill(20) '000000000000djywanan' 将字符串格式化:format()1)使用位置参数: >>> 'I like {1},{0},in particular {2}.--{2}'.format('music','dance','DJY') 'I like dance,music,in particular DJY.--DJY' >>> list1=['music','dance','DJY'] >>> 'I like {},{},in particular {}'.format(*list1) 'I like music,dance,in particular DJY' 位置参数不受顺序约束,只要format里有对应的参数值即可为{},参数索引从0开,传入位置参数列表可用*列表。2)使用关键字参数: >>> hash1={'music':'psychedelic rock','dance':'Latin','name':'DJY'} >>> 'I like {music},{dance},in particular {name}'.format(**hash1) 'I like psychedelic rock,Latin,in particular DJY' >>> hash1={'music':'psychedelic rock','dance':'Latin','name':'DJY'} >>> 'I like {music},{dance},in particular {name}'.format(music='classical music',dance='tango',name='FXW') 'I like classical music,tango,in particular FXW' 关键字参数必须要一一对应,以**字典格式用字典输入关键字参数。3)如果想输出{} >>> '{{0}}'.format('djy') '{0}' 4)精度与进制转换: >>> '{0:.2f}{1}'.format(1/2,'km') '0.50km' >>> '{0:x}'.format(10) #转换成十六进制 'a' >>> '{:,}'.format(123456789) #千分位格式化 '123,456,789' 5)填充与格式化:{填充字符} >>> '{0:*>10}'.format(20) #<左对齐,>右对齐,=居中 '********20' 以encoding指定的编码格式对字符串进行编码,以decoding指定的解码码格式对字符串进行解码:encode(encoding='utf-8',errors='strict')、decode(encoding='utf-8',errors='strict') Python3中,以str型代替了unicode类型,经过编码后变为了字节类型(bytes),而但是两个函数的使用方法不变: >>> a='djy' >>> a_utf8=a.encode("UTF-8") #以UTF-8编码对a进行编码,获得bytes类型对象 >>> a_utf8.decode("UTF-8",'strict') #对a_utf8进行解码得到的结果,将无法还原原来的字符串内容 'djy' END!
数学常量 圆周率:pi; 自然常数:e。 数学函数 返回数字的绝对值,且值的类型取决于原参数的类型(复数返回浮点型):abs( x )x---数值 >>> abs(-1.23) 1.23 >>> abs(3+4j) 5.0 返回浮点数或整数的绝对值,且值的类型只能是浮点型:fabs( x )x---数值 >>> import math >>> math.fabs(-1.23) 1.23 返回数字上取后的整数:ceil( x )x---数值 >>> import math # ceil(x)不能直接访问,需先导入 math 模块 >>> math.ceil(-0.74) 0 返回数字下舍后的整数:floor(x)x---数值 >>> import math # floor(x)不能直接访问,需先导入 math 模块 >>> math.floor(-0.74) -1 返回x的小数部分与整数部分,注意整数部分以浮点型表示:modf(x)x---数值 >>> import math # modf(x)不能直接访问,需先导入 math 模块 >>> math.modf(-111.222) (-0.2219999999999942, -111.0) 返回浮点数x的四舍五入值:round(x [, n]) x---浮点数; n---精度 >>> round(111.222333444, 6) 111.222333 返回x的y次方:pow() 1)内置方法 >>> pow(2, 3) #把参数作为整型 8 2)导入math模块 >>> import math #把参数作为浮点型 >>> math.pow(2, 3) 8.0 返回数字x的平方根:sqrt(x)x---数值 >>> import math # sqrt(x)不能直接访问,需先导入 math 模块 >>> math.sqrt(100) 10.0 返回x的自然对数:log(x)x---数值表达式 >>> import math # log(x)不能直接访问,需先导入 math 模块 >>> math.log(0.1353352832366127) -2.0 返回x的指数:exp( x )x---数值表达式 >>> import math # exp(x)不能直接访问,需先导入 math 模块 >>> math.exp(-2) 0.1353352832366127 返回给定参数的最大值,参数可以为序列:max( x, y, z, .... )x,y,z---数值 >>> max(1, 3, 2) 3 返回给定参数的最小值,参数可以为序列:min( x, y, z, .... )x,y,z---数值 >>> min(1, 3, 2) 1 随机数函数 从序列的元素中随机挑选一个元素:choice(seq)seq---列表,元组或字符串 >>> import random >>> print('DJY,are you handsome?',random.choice(['--SURE!','--NOT AT ALL!','--GUESS?'])) DJY,are you handsome? --SURE! 从给定的范围返回随机项:randrange ([start,] stop [,step])start---指定范围内的开始值,包含在范围内; stop---指定范围内的结束值,不包含在范围内;step---步长,默认为1。 >>> import random >>> random.randrange(11, 999, 12) 587 返回随机生成的一个实数,它在[0,1)范围内: random() >>> import random >>> random.random() 0.5895961190959703 改变随机数生成器的种子,可以在调用其他随机模块函数之前调用此函数:seed(x)x---改变随机数生成器的种子,可不设置 >>> import random >>> random.seed(10) >>> random.random() 0.5714025946899135 >>> random.seed(10) >>> random.random() 0.5714025946899135 随机生成一个在[x,y]范围内的实数:uniform(x, y)x---最小随机数; y---最大随机数; >>> import random >>> random.uniform(0.15,578) 168.77383737106067 返回随机排序后的序列:shuffle (lst)lst---列表 >>> import random >>> list1 = ['酷狗音乐','网易云音乐','QQ音乐', '虾米音乐'] >>> random.shuffle(list1) >>> list1 ['QQ音乐', '虾米音乐', '酷狗音乐', '网易云音乐'] 三角函数 返回x的反正弦、反余弦弧度值:asin(x) 、acos(x)x--- -1到1之间的数值 >>> import math >>> math.acos(0.55) 0.9884320889261531 >>> import math >>> math.asin(0.55) 0.5823642378687435 返回x的反正切弧度值:atan(x)x---数值 >>> import math >>> math.atan(0.55) 0.5028432109278609 返回给定的 X 及 Y 坐标值的反正切值:atan2(y, x)x,y---数值 >>> import math >>> math.atan2(0.55,0.55) 0.7853981633974483 返回x的弧度的正弦值、余弦值、正切值:sin(x)、cos(x)、tan(x)x---数值 >>> import math >>> math.sin(0.55) 0.5226872289306592 >>> import math >>> math.cos(0.55) 0.8525245220595057 >>> import math >>> math.tan(0.55) 0.6131052132881357 返回欧几里德范数 sqrt(x*x + y*y):hypot(x,y) x,y---数值 >>> import math >>> math.hypot(1,2) 2.23606797749979 将弧度转换为角度:degrees(x) x---数值 >>> import math >>> math.degrees(-2) -114.59155902616465 角度转换为弧度:radians() x---数值 >>>import math >>> math.radians(-2) -0.03490658503988659 最后有点感想,对于函数,往往看中的是它的功能以及返回值,有些函数功能很类似,但是不要忽略了,他们运行速度的微略差距,也许很不起眼,但是并不渺小。 END!
变量 顾名思义,就是程序运行中值能改变的量,而且在变量使用之前,需要对其赋值。变量名的命名及使用规则: 可以包括字母、数字、下划线,但不能以数字开头; 字母区分大小写,即同一字母的大小写代表不同的变量; 尽可能根据变量数据特点命名,可提高程序的可读性; 变量名不要和Python的BIF重名,虽然Python中可以对BIF进行赋值,但是实际编程中很可能会遇到BUG,在编译器中BIF为紫色。 等号"="是赋值的意思,左边是变量名,右边是值。1) 单变量赋值 >>> year=2018 2)多变量赋值 >>> a = b = c = 1 >>> a, b, c = 1, 2.0, 'DJY' 数据类型 Python有五个标准的数据类型: numbers(数字):int,float,bool,complex str(字符串) list(列表) tuple(元组) dict(字典) set(集合) int Python可以处理任意大小的整数,例如: >>> -12345678*9876543 #输出结果 -121932619631154 计算机中常使用十六进制表示整数,例如:0xFFEC,0xAABB。 float 有小数点的数字就可以理解为float型数据,不区分单双精度,并且可以通过round()等函数对其精度进行控制,例如: >>> round(11.23456789,2) #输出结果 11.23 对于很大或者很小的数,我们通常采用科学计数法,把10用E代替,例如:1.23E6,2.04E-23。 bool 一个布尔值只有True、False(注意大小写)两种值; 布尔值可以进行not、and和or运算:not是非运算,把 True 变成 False,False 变成 True; and是与运算,值都为 True时,结果才为True;or是或运算,只要有一个值为 True,结果就是 True。 complex >>> (2+3j)*(4+6j) #输出结果 (-10+24j) >>> (1+2j).imag #输出结果 2.0 str 由数字、字母、下划线组成,表示方法有单引号,双引号,三引号(三单引号和三双引号)三种,例:'djy',"djy",''' djy''',"""djy""",注意Python中单字符也是字符串; list 是一种有序的集合,可以包含整数,浮点数,字符串,对象,可以随时添加和删除其中的元素。 普通列表 >>> player=['酷狗音乐','网易云音乐','QQ音乐','虾米音乐'] >>> type(player) <class 'list'> 混合列表 >>> music=[1996,'11:59','IF','人间失格',['华晨宇','丁可']] >>> type(music) <class 'list'> 空列表 >>> empty=[] >>> empty [] tuple tuple 和 list 非常类似,只是,tuple一旦创建完毕,就不能修改了。 普通元祖 >>> tuple1=1, #或者tuple1=(1, ) 注意“,”是关键 >>> type(tuple1) <class 'tuple'> 空元祖 >>> tuple1=() >>> tuple1 () dict dict可存放任意类型对象,但它是通过键和键值来存储,其中键不可变且不允许同一个键出现两次,值可以取任何数据类型。dict = {key1 : value1, key2 : value2 } >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> type(dict1) <class 'dict'> >>> dict2= dict(singer='GEM', sex= 'female', song='查克靠近') >>> dict2 {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> type(dict2) <class 'dict'> 另外,通过给键值赋值的方式创建字典时,如果键值存在则自动更新键值内容,如果不存在此键值将会自动在字典里添加此键值。 set set 和 list 类似,但是set中的元素不可重复,而且是无序的,这点和 dict 的 key很像。 >>> set1= {'酷狗音乐', '网易云音乐', '虾米音乐'} >>> type(set1) <class 'set'> 数据类型转换 将一个字符串或数字转换为整型:int(x[,base]) x---字符串或数字; base---进制数,默认十进制; >>> int() 0 >>> int(1) 1 >>> int(1.8) 1 >>> int('0xff',16) 255 将整数和字符串转换成浮点数:float(x)x--- 整数或字符串 >>> float() 0.0 >>> float(1) 1.0 >>> float('123') 123.0 将一个字符串或数转化为复数或创建一个复数,如果第一个参数为字符串,则无需设置第二个参数:complex([real[, imag]])real---int,float,str; imag---int,float; >>> complex() 0j >>> complex(1) (1+0j) >>> complex("1") (1+0j) >>> complex("1+2j") # 这个地方"+"号两边不能有空格,否则会报错 (1+2j) 将对象转化为字符串型:str(x)x---对象 >>> str1=100 >>> str(str1) '100' >>> dict1= {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> str(dict1) "{'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'}" 计算字符串中的有效Python表达式,并返回一个对象:eval(expression[, globals[, locals]])expression---表达式。 globals---变量作用域,全局命名空间,如果设置,则必须是一个字典对象。locals---变量作用域,局部命名空间,如果设置,则可是任何映射对象。 >>> x = 2 >>> eval("x + 4") 6 >>> eval('pow(2,2)') 4 将序列转换为元组:tuple( seq )seq---序列 >>> tuple((1,2,3)) #将tuple转化为tuple (1, 2, 3,) >>> tuple([1,2,3]) #将list转化为tuple (1, 2, 3) >>> tuple({1:2,3:4}) #将dict转化为tuple (1, 3) 将元组转换为列表:list( seq )seq---序列 >>> tuple1=(1,'djy') >>> list1=list(tuple1) >>> list1 [1, 'djy'] 转化为一个无序不重复元素集,还可计算交集、并集、差集的集合:set([iterable])iterable--- 可迭代对象 >>> set1='djy' >>> set(set1) {'d', 'y', 'j'} >>> set1='djy' >>> set2='fxw' >>> set(set1) & set(set2) #取交集 set() >>> set(set1) | set(set2) #取并集 {'w', 'y', 'j', 'f', 'd', 'x'} >>> set(set1) - set(set2) #取差集 {'d', 'y', 'j'} 创建一个字典:dict(kwarg)、dict(mapping, kwarg)、dict(iterable, **kwarg) **kwargs---关键字;mapping---元素的容器;iterable---可迭代对象; >>> dict(singer='GEM', sex='female', song='查克靠近') {'singer': 'GEM', 'sex': 'female', 'song': '查克靠近'} >>> dict(zip(['A', 'B', 'C'], ['a','b','c'])) # 映射函数 {'A': 'a', 'B': 'b', 'C': 'c'} >>> dict([('A','a'),('B','b'),('C','c')]) #可迭代对象 {'A': 'a', 'B': 'b', 'C': 'c'} 创建一个不可变集合:frozenset([iterable])iterable---可迭代的对象,比如列表、字典、元组等 >>> a = frozenset('fxwdjy') >>> a frozenset({'w', 'y', 'f', 'j', 'd', 'x'}) 将一个字符转换为它的十进制值:ord(c)c---字符 >>> ord('a') 97 将一个整数转换为一个八进制、十六进制字符串:oct(x)、hex(x)x---10进制整数 >>> oct(10) '0o12' >>> hex(10) '0xa'
快捷键(常用) 新建文件:Ctrl+N; 打开文件:Ctrl+O; 打开模块:Alt+M(先选中模块,再按下此快捷键,会打开该模块的python源码); 浏览模块:Alt+C; 路径浏览: Alt+FP; 光标当前所在行列:IDLE右下角有显示; 跳到目标行号:Alt+G; 调出上一条命令:Alt+P; 调出下一条命令: Alt+N; 跳到开头:Ctrl+uparrow; 跳到结尾:Ctrl+downarrow; 跳到上一行开头:Ctrl+leftarrow; 跳到下一行开头:Ctrl+rightarrow; 全选:Ctrl+A; 缩进代码:Tab/空格(注意:这两种方式缩进量可能不同,会导致运行时会报错“unexpected indent”,所以,编程时最好只采取一种;如果已经混用,可以在编程结束后,先Ctrl+A、再Alt+5/6、再OK,三步即可解决); 补齐文中出现过的单词:Alt+/; 查找:Ctrl+F; 再次查找:Ctrl+G; 查找选中部分:Ctrl+F3; 查找文件:Alt+F3; 替换:Ctrl+H; 撤销:Ctrl+Z; 反撤销:Ctrl+Shift+Z; 注释代码行:Alt+3; 取消注释代码行:Alt+4; 全选:Ctrl+A; 运行代码:F5; 保存代码:Ctrl+S; 另存为:Ctrl+Shift+S; 保存副本:Alt+Shift+S; 打印窗口:Ctrl+P; 关闭:Alt+F4; 退出:Ctrl+Q; 打开Python文件:F1; 单步调试:Alt+DD; 定位到错误位置:Alt+DG(先定位到错误行,再按下此快捷键); 显示错误历史:Alt+DA; 重新启动shell:Ctrl+F6 。 操作符 按优先级由高到底排列: 幂运算[**]; 正负号[+ -]; 算数操作符[* / // % + -]; 比较操作符[< <= > >= == != <>]; 逻辑运算符 not and or 。 注:编程时适当使用(),可增加程序的可读性。 BIF Built-in functions的缩写,意为内置函数,编程时通过使用内置函数实现各种功能。本文不具体分析每个BIF的具体使用,只说明查找BIF功能的方法,具体使用会在以后的文章中结合实例分析。 在IDLE中输入: dir(__builtins__) 显示如下列表,其中全都为小写的字符串为BIF。 如果想知道某个BIF的功能,直接在IDLE内查找即可(这里以super()函数为例),输入以下代码: help(super) super()函数的功能及使用方法显示如下: 如果有些英文看不懂,可以借助翻译软件。 有了以上了解,不禁发现Python和MATLAB有很多相似之处,这里借助奥特曼超人很久之前的一段话,浅略地对两者进行比较: 国外近几年比较流行的是MATLAB,但它是商用,和Oracle一样,需要付费,且价格不菲。如果使用Python做科学计算,一方面完全免费,同时众多开源的科学计算库都提供了Python的调用接口,用户可以在任何计算机上免费安装Python及其绝大多数的扩展库;其次Python是一门更易学、更严谨的程序设计语言,它能让用户编写出更易读、易维护的代码;最后Python有着丰富的扩展库,可以轻易完成各种高级任务,开发者可以用Python实现完整应用程序所需的各种功能。 END!
一、了解Python Python的定义 Python是一种面向对象的服务器端解释性、开源、非编译的脚本语言,可单独使用,也可作为框架组成部分使用。 Python的特点 1.适用领域 web开发:django、pyramid、tornado、bottle、flask、web.py。 网络编程:twisted、requests、scrapy、paramiko。 科学运算:scipy、pandas、ipython。 GUI图形开发:wxpython、pyqt、kivy。 运维自动化:openstack、saltstack、ansible、腾讯蓝鲸。 2.不适用领域 贴近硬件的代码(首选C)。 移动开发(iOS/Android都有各自的开发语言)。 Python的一些编程语言功能 有多种基本数据类型:数字(浮点型,复数型和无限长的长整型),字符串(包括ASCII和Unicode),列表和字典。 Python支持类和多继承。 代码可以加载到模块和包中。 支持错误捕捉。 混合不兼容的类型(例如试图添加一个字符串和一个数字)会引发异常,所以错误会很快被捕获。 Python包含高级编程功能,如生成程序和列表。 Python的自动内存管理,让你不必再手动分配和释放内存。 二、安装Python 1.点击链接进入Python官网2.在当前页面底部,点击Downloads下的windows(根据自己系统选择) 3. 系统是32bit的选x86,64bit选x86-64, 关于选python2.x还是python3.x,如果初学python我建议学python3.x,如果以前用过python2.x,建议你参考python2 or python3; web-based installer 是通过联网的方式进行安装; executable installer 是通过可执行文件(*.exe)的方式进行安装; embeddable zip file 是一个嵌入式压缩文件,可以集成到其它应用中。我选择的是Windows x86-64 executable installer。 4.下载后,将电脑运行中的杀毒软件退出,以管理员身份运行(*.exe)文件,开始安装Python。 注意最下面的 Add Python 3.7 to PATH,意思是,把python的安装路径添加到系统路径下面。如果勾选,不用再手动配置环境;如果不勾选,需要安装后手动设置路径,这里推荐勾选。5.点击Install Now(默认安装路径和安装文件),安装过程约1分钟。6.如果安装过程出现以下问题: 很可能是杀软没退出,退出后重试。7.界面显示Setup was successful 说明安装成功了,点close关闭即可。8.验证是否成功安装。 快捷键Win+R,调出运行窗口,输入cmd,然后确定; 再输入python,显示如下 说明安装成功。注意:如果在上述第4步中没有勾选Add Python 3.7 to PATH,这里会显示‘python ’不是内部或外部命令,也不是可运行的程序或批处理文件。 三、启动Python 1.双击IDLE启动python; 2.在 >>> 后键入语句 print("Hello,DJY!"),回车; 3.进行简单尝试: END!