python r怎么用list累加做累加

Latest version is 3.4
Download now! &
&Using ANTLR
&About ANTLR
Support StringTemplate, ANTLR Project by making a donation!
Terence often pays for things like the antlr.org server, conference travel, and this site design (that alone cost US$1000). Buy him a beer)
Share List
Earlence Fernandes Fri Jun 22,
This package contains updated instructions and documentation for my earlier port.
Eric Taucher Fri Mar 16,
Robinson Unification Algorithm in F# - Learning Version
YANG Guifu Mon Dec 5,
It is a 6-days-blog attatched, which descibes step by step how to
Kenney Westerhof Wed Sep 7,
A VIM syntax file for StringTemplate files (.stg etc..)
M醨ton Papp Wed Jul 20,
A project for ANTLR D target at sourceforge.
Juergen Pfundt Mon May 16,
[updated] A task for Ant that knows about building ANTLR v3 grammars.
Earlence Fernandes of CRePE project Fri Feb 4,
A tarball that can be overlayed on top of an existing antlr 3.3 distribution.
Just download it, extract and copy over to an android source directory, run a make and everythings set. Context related policy enforcement for Android website: .
Adam Retter Thu Oct 28,
ANTLR 3 grammar and generated Java parser for XQuery with Update, Scripting and Full Text extensions
Sun Oct 10,
mdsl is a simple interpreted language built on top of java.
Ivan Mosquera Sun Oct 3,
For educational purposes. It's a java desktop apps which features a C-subset interpreter and It draws how the program evolvers while is interpreted. (direct link to C grammar,walker..: /ivmos/Ikuspro/tree/master/src/ikuspro/interprete/c/)
Ivan Mosquera Thu Sep 30,
/translate?js=y&prev=_t&hl=es&ie=UTF-8&layout=1&eotf=1&u=http://ivanmosquera.net/index.php//ikuspro-es-libre/&sl=es&tl=en
Robert Baruch Thu Nov 12,
This zip file contains Unicode_5.2.0_Lexer.g, a set of lexer fragments you can include in your grammar to recognize a given character as any of the possible Unicode general categories. Need a Unicode lower case letter? UnicodeCategoryLl will do it. How about a number? UnicodeCategoryNd is what you need.
Davyd Madeley Fri Nov 21,
I found an old vim syntax highlighter on antlr-interest,
but it didn't deal very nicely with some things in my grammar.
I've updated it and thought I'd share it with anyone who might be interested.
Add it to ~/.vim/syntax/And add something like this to your .vimrc:au BufRead,BufNewFile *.g
set syntax=antlr3
Sun Microsystems / NetBeans Tue Jun 3,
Sun's NetBeans team has produced a version of ANTLR v2 that is very highly tuned to get extremely high performance.
See also .
Loring Craymer Thu Nov 29,
Yggdrasil documentation
Scott Fortmann-Roe Thu May 3,
A simple interpreter and compiler for a subset of C supporting if-statements, loops, integers, functions, and arrays. The interpreter is implemented using a tree grammar and the compiler targets
intermediate representation. Tested with ANTLR 3.0b7.
Joseph Grace Sun Mar 25,
A simple rakefile.rb to build antlr v3 (antlr.jar) from source.
Includes clean, clobber, and default (antlr.jar) targets.
Much simpler and self-explanatory than the ant file included with distribution.
Alex Stojan Mon Mar 5,
This is a compiler for a simple statically-typed language that supports basic constructs like loops, if-then statements, pointers, functions, and arrays. It generates assembly files with instructions for a simple stack-based virtual machine (also included in the ZIP file). Both the compiler and the VM are implemented in C++, using ANTLR 2.7.5 for parsing and AST processing.
stefan@amiq.ro Thu Jan 18,
This is a XEmacs mode for string template files, that I developed some time ago.
Kay R鰌ke Thu Jan 11,
This jar file contains a build of the latest depot version of ANTLR v3, due to requests from the mailing list.
Sat Oct 7,
Yggdrasil documentation
Loring Craymer Sat Oct 7,
Early Yggdrasil release.
Based on ANTLR 3.0b4
Loring Craymer Tue Jul 25,
This one has the correct BisonReader.java
Loring Craymer Sat Jul 22,
Fixes token constructor on line 91 to be ANTLR 2.7.6 compatible
Gerrie Myburgh Thu Jun 29,
sentence generator for a antlr grammar
Mon Jun 26,
Minor bug fixes.
Mon Jun 26,
Translates bison/yacc grammars to ANTLR 2.7 grammars.
Loring Craymer Thu Jun 1,
Source to source ANTLR grammar translator
Adriano Bedeschi Sun Apr 9,
Antlr.NET 2.7.6 converted from antlr.jar with IKVM - http://www.ikvm.net/
Kunle Odutola Thu Dec 8,
Yet Another C# Grammar For ANTLR (implementation language is also C#). It is probably more complete and includes both an ANTLR and a C# Flex lexer.
Arturo Montes Fri Sep 23,
This is a port for ANTLR java to C++. This is like ANTLR C++ 2.7.4. I will be sending instructions. Keep follow. Best regards, Arturo Montes
Colm McHugh Wed Jul 6,
Antlr 2.7.5 installation, built on RedHat EL 3
Ken Wenzel Mon May 30,
Two Vim syntax files for StringTemplate (angle bracket and dollar delimited).
Doug Holton Sat May 7,
This is antlr.jar converted to antlr.exe using IKVM (http://www.ikvm.net/).
It runs on .NET or Mono (in Windows or Linux).
Also included are the IKVM.GNU.Classpath.dll and IKVM.Runtime.dll dependencies.
To create your own exe, download IKVM and run the command:"ikvmc.exe -target:exe -main:antlr.Tool antlr.jar"
Patrick Phelan Wed May 4,
A not entirely successful program to convert 500,000 lines of aged Progress 4GL code to PHP. It is not a full 4GL interpreter, and only covers the limited grammar subset of 4GL I had in front of me, and is clearly a program meant to be run only once. Still, it might be useful as a guide to others doing something similar, if only to show what not to do. (Save as.. tar/bzip2)
Marq Kole Mon Apr 25,
A python port of Terence's example .
Uses new Python StringTemplate port released April 25, 2005.
Francis ANDRE Fri Apr 22,
A MSVC7.1 solution for building antlr.dll from sources ANTLR 2.7.5 with 3 examples included (calc, idl, treewalker). The vc71.zip should unzipped under the installation dir of the source delivery.
George Yu Wed Mar 23,
Antlr VB.Net extension is a "hack" implementation for generating parser in VB.Net code.
Steve Sarandos Fri Mar 11,
This build fixes a bug that occurs when using the "separator" construct.
Andre K. Thu Feb 10,
Visual J# 2003 Project. Compiles the antlr sources to a antlr.exe tool running on the .NET platform.
Steve Sarandos Thu Feb 3,
StringTemplate 2.1 ported to C#
Mark Malakanov Sat Jan 29,
Many enchancements and fixes. More accuracy. Two styles of diagrams.
Haefelinger Thu Jan 13,
ANTLR 2.7.5 (rc2) as MSI based installation for Windows. Contains language support for C++ (VS 2oo3), Python, Java and C# (.NET 2003).
Haefelinger Thu Jan 13,
ANTLR 2.7.5 for Cygwin - second try. Will now install correctly in /usr instead of /.
Charles Crichton Wed Jan 12,
This patch corrects a bug in the "Save as HTML and multiple files" menu item of the Syntax Diagram Generator 2 tool.
Haefelinger Wed Jan 12,
ANTLR 2.7.5rc2 for Cygwin - Initial proposed package.
Haefelinger Wed Jan 12,
RPM for Linux - compiled on Mandrake 1o but supposed to work on other distros as well. Please check and provide feedback.
Haefelinger Wed Jan 12,
Initial version for Cygwin - not yet approved. Use it as is, no warranty.
Mark Malakanov Sat Dec 25,
Based on "ANTLR Syntax Diagram Generator" (Jennifer Zheng), this new tool adds functionality of saving diagrams in variety of graphic formats. Saving whole diagram to raster image formats like PING or JPEG, to vector image format SVG. Saving into multiple raster images and one binding HTML
with hyperlinks for navigation among rules and elements.
Ric Klaren Wed Dec 1,
Development snapshots, mainly for the C++ output mode, but often also contains fixes for the other codegenerators.
Terence Parr Sun Nov 21,
A java-AST tree walker grammar containing actions to spit the tree back to java text.
A bit out of date (old 1.3 grammar).
Only works well enough for a class project. ;)
Now I'd probably use StringTemplate to generate the output.
Wolfgang Haefelinger Thu Nov 4,
This is a initial version of ANTLR for Python. Right now lexer is supposed to work for non-filtering grammars. Please read enclosed README.txt for further details. Code generator for Parser and Walker are in progress...
Barry Kelly Mon Oct 18,
antlr-2.7.4 without any dependencies on CYGWIN1.DLL or any other CYG*.DLL cygwin dlls.
Krzysztof Leszczynski
Tue Sep 7,
This is a PDF manual generated from today's (i.e. Sep 7 2004) sources at http://www.antlr/doc/ It has better margins than pdf I previously found, also I stripped navigation bars, search boxes, etc.
The most recent version and the script for regenerating the PDF is at my ftp site: http://ftp.camk.edu.pl/private/chris/antlrman/ Please let me know when the documentation is updated, so I can regenerate the PDF file.
Jesus Ramon Aviles Vasques() Tue Jul 27,
Library for run code generate by antlr in c++
Eric Mahurin Mon Jul 26,
A C PreProcessor done completely in a stack of ANTLR lexers.
This could be integrated with an existing C or whatever lexer to do the preprocessing and tokenizing in one step.
Tom Verbeure Mon May 17,
GCJ compiled version of ANTLR 2.7.4 on Cygwin as described in my article "Getting ANTLR to run on Cygwin and GCJ" in the articles section. Zipped with gzip...
Peter Sprenger Sun May 16,
This pdf file contains the ANTLR Reference Manual from antlr.org. The pdf document makes it much easier to print the manual in one piece and to search for keywords.
Neeraj Sharma Wed May 12,
Makefile is also provided if you want to build antlr yourself.
Please note that on "ldd cantlr": libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x) libgcj.so.4 => /usr/lib/libgcj.so.4 (0x) libm.so.6 => /lib/libm.so.6 (0x407e6000) libpthread.so.0 => /lib/libpthread.so.0 (0x) libz.so.1 => /usr/lib/libz.so.1 (0x) libdl.so.2 => /lib/libdl.so.2 (0x) libc.so.6 => /lib/libc.so.6 (0x) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x)
Anakreon Mejdi Wed Apr 14,
An enhanced version of annotation tool created by Bogdan Mitu.
C?sar L?pez Natar?n. Wed Mar 31,
Makefile for building C# code generation and runtime support
on Linux for use with Mono or other CLI implementation for antlr-2.7.3
Just copy this file to antlr-2.7.3/lib/csharp/src
Type: "make -f makefile.mono"
Copy the resulting antlr.runtime.dll and antlr.runtime.dll.so to the directory where your CLI-based assemblies go.
Mark Swann Wed Mar 24,
ANTLR Win32 binary for V 2.7.3 compiled with gcj.
Jennifer Zheng Wed Mar 17,
[Submitted by Terence Parr] View your ANTLR grammars as syntax diagrams.
This prototype demonstrates a multi-phase ANTLR translator.
Phases read the grammar, compute elements widths, layout elements, draw elements, etc...
Very easy to use: just send your grammar file into edu.usfca.syndiag.Main via System.in and it will display a Swing window with your syntax diagram.
Ultimately I hope to use something like this to display ambiguous paths in your grammar during analysis.
Aaron Sawdey Fri Feb 20,
[submitted by Terence Parr]
This PCCTS grammar for fortran77 doesn't seem to have a PCCTS lexer spec (Aaron seems to have used a modified lexer from F2C).
Anyway, might be useful to somebody.
Neeraj Wed Feb 18,
The given html file demonstrates the way to compile antlr libs for MinGW taking antlr-2.7.1 as the antlr package.
Neeraj Wed Feb 18,
Windows binary for antlr-2.7.1 using MinGW
Bogdan Mitu Wed Feb 11,
A framework for creating "syntax aware text components" using ANTLR lexers and parsers. Included are syntax highlight for
several languages and on-the-fly reparsing of Java source files (the token-chain and the AST are updated on each key pressed).
Jim OConnor Wed Jan 7,
Summary of email sent to newsgroup at yahoo. Input: *.java files, jar files, or a directory structure Output: An XML document with a hierarchical representation of packages, classes and references. Installation and use: "java antlr.Tool" the g files (javatree.g is the supergrammar for defs.g, refs.g, and prerefs.g) Look in Main.java, MyOutput.java and CodeProject.java for flags. Enjoy! Jim.
Santhosh Kumar T Wed Jan 7,
View the tokens in Token Stream visually and see from which location this token referes to in the given input.
Mon Jan 5,
A 1st attempt of a Infomix 4GL Grammar, works with all the files i tried, but need some improvements
Ashish Aggarwal
Sun Nov 30,
As every new user do face problems in building antlr on windows,using cygwin/java/gcc, I (on behalf of our company, Atrenta), would like to share with you all this working recipe on "How To Build Antlr On Cygwin".
Luca Di Gaspero Sat Nov 22,
The current linux ANTLR binary relies on the version of the gcj library employed for compiling it (i.e., it is not fully static). For instance, on SuSE Linux 8.2 it does not work at all.
Here is a makefile so you can do a local build.
Steve Sarandos Wed Nov 5,
A port of StringTemplate to C#
Arnar Birgisson Sat Oct 4,
This zip file contains compiled dll versions of the ANTLR C++ runtime. Both release and debug builds are provided, with a symbols file as well.
This build is based on Ric Klaren's development version of ANTLR 2.7.2 (2.7.3) dated .
Amol Dharmadhikari Wed Sep 17,
The current version is just the jython code generator i.e. to access it you will need some java classes and so you need jython.
I also include the
that has the python code generator files.
Enrique Jose Garcia Cota (kikito) Thu Jul 31,
antlraux is a support library for antlr. It features extended one Token class, several extended AST nodes and contextual information management (Scopes+Declarations+Types). It also includes a command-line parser. It is written in java (sorry, still no C++ version) and distributed under the GPL license.
Stefan Ziel (stefan..br) Fri Jul 25,
Example how to convert an AST to XML by implementing the org.xml.sax.XMLReader Interface. This example uses the Java parser.
Andy Tripp Thu Jul 17,
JavaEmitter prints reasonably formatted Java code from an ANTLR AST.
Tomasz Jastrzebski Sun Jul 6,
J# Project files - allows Antlr Code Generator to be built in VS.Net 2003 environment
Tomasz Jastrzebski Sun Jul 6,
Net signed executables buit with J# compiler
Kunle Odutola Fri Jul 4,
An update for the C# runtime and code-generator in ANTLR 2.7.2 only. Unzip the archive into your ANTLR 2.7.2 directory. It contains only the modified files and can be applied to other 2.7.2 services releases such as Ric Klaren's latest C++ snapshot (if both C++ and C# are important to you).
Robert Colquhoun Fri Jul 4,
3 Patches for antlr 2.7.2: 1) Remove import statements in generated antlr code - prevents name clashes and warnings when used with eclipse 2) Fix to stopping ClassCastException's that occur in protected tree walker rules which legally match nothing 3) Java 1.1 compatibility patch.
Minor changes to remove jdk1.2 classes and methods
Rodrigo B. de Oliveira
The point of this sample is to show how to combine a custom TokenStream implementation (TokenStreamRecorder) with the antlr stream multiplexing facility (TokenStreamSelector) to parse expressions inside double quoted strings:print "3*2-1: ${3*2-1}" The sample actually implements a very simple interpreter and allows "programs" to be run interactively.
Terence Parr
A parser for ANTLR's metalanguage that builds an AST representing the grammar.
Included is antlr.tree.g that walks the trees and antlr.print.g that walks the trees and spits the grammar back out.
Note that it ignores everything except stuff relevant to rules and possibly even ranges at the moment.
Terence Parr
This code is a first experiment into a Java cross referencing tool (uses ANTLR 2.7.2).
It is not finished and I can't even remember what state it is in.
Literally it may not compile.
I suspect it requires some internal jGuru code to compile/run.
Also note that the java.g stuff might be out of sync with the latest at the antlr. though I think I used this to make the improvements for the antlr.org site.Python教程学习简记1--Python数据类型和变量 字符串和编码 list和tuple 条件判断 循环 dict和set
Python教程学习简记1--Python数据类型和变量 字符串和编码 list和tuple 条件判断 循环 dict和set
[摘要:本文首要是进修Python基本:
Python数据范例战变量 字符串战编码 list战tuple 前提判别 轮回 dict战set
本文依据廖雪峰的民圆网站-Python教程,卖力进修,一步一步真操并]
本文主要是学习Python基础:
Python数据类型和变量 字符串和编码 list和tuple 条件判断 循环 dict和set
本文根据廖雪峰的官方网站-Python教程,认真学习,一步一步实操并且详细记录。
在此,特别感谢廖雪峰老师。
Python2.x与Python3.x
之后补上。。。。。。
升级Ubuntu15.10系统的Python
Ubuntu15.10系统默认安装的Python为2.7.10
安装Python3.5
sudo apt-get install python3.5
注:由于Ubuntu底层采用的是Python2.*,Python3与Python2是互不兼容的,但是不能卸载Python2,只需要将默认的Python指向Python3
之前安装的Python3.5默认是安装在/usr/local/lib/python3.5目录下,需要删除默认python link文件,重新建立连接关系
rm /usr/bin/python
ln -s /usr/bin/python3.5 /usr/bin/python
第一个Python程序
直接在python交互式命令行中输入想要执行的代码,回车就可以立即得到代码的执行结果
python打印指定的文字,使用print()函数;将打印的文字用单引号或者双引号括起来!
print("hello python")
print('hello world')
Python基础
Python是一种编程语言,所以它也就有自己的一套语法规则。
编译器或者解释器负责把符合语法规则的程序代码转换成CPU能够执行的机器码,然后执行。
Python的语法比较简单,采用缩进的方式,写出来的代码如下所示:
(官网截图)
以#开头的语句为注释,注释是给开发者看的,可以使任意内容,解释器会忽略掉注释。
其他每一行都是一个语句,当语句以冒号“:”结尾时,缩进的语句视为代码块。
缩进能够强迫我们写出格式化的代码,但是没有规定缩进是几个空格还是Tab。按照约定俗成的管理,应该始终坚持使用4个空格的缩进。
特别注意:Python程序是大小写敏感的。
输入和输出
之前有提到print(),那就先从输出开始
用print()将所要输出的字符串作为参数添加在括号里面,并用单引号或者双引号括起来
print('hello python !')
print()函数也可以接受多个字符串,之间用逗号“,”隔开,就可以连成一串输出:
print('I want to speak good english !')
print("I","want","to ","speak","good","english","!")
注:print()函数会依次打印每个字符串,遇到逗号“,”会输出一个空格
print()也可以打印整数,或者计算结果,例如:
&&& print(888)
&&& print(888+111)
人性化打印计算结果:
&&& print("555+111=",555+111)
555+111= 666
下来我们说一说输入:
和其他语言一样,python给我们提供了输入函数input(),可以让用户输入字符串,并且存放到一个变量里面
&&& name=input()
当输入name=input()并且按下回车之后,python交互式命令终端就等待你的输入了。这时你可以输入任意字符串,然后按回车完成输入。
输入完成后,不会有任何提示,python交互式命令终端又回到&&&状态。
刚才将输入的内容存放到变量name里面了,我们可以直接在命令行里面输入变量名name,查看变量的内容。
打印name变量的内容,除了直接在命令行里面输入变量名name回车查看变量内容之外,还可以使用我们之前学到的print()函数:
&&& print(name)
&&& name=input("please enter your name : ")
please enter your name : hjr
&&& print('hello,',name)
hello, hjr
&&& print(1024*768)
数据类型和变量
Python可以处理任意大小的整数(包括负整数),在程序中的表示方法和数学上的写法一模一样。例如:
浮点数,即:小数。之所以称为浮点数,是因为按照科学计数法表示时,一个浮点数的小数点位置是可变的,比如:1.23x109(上标)和12.3x108(上标)是完全相等的。
浮点数可以用数学写法,如:1.23,3.14,-9.01等。
对于很大或者很小的浮点数,就必须使用科学计数法表示,把10用e代替,1.23x109(上标)就是1.23e9或者12.3e8,0.000012可以写成1.2e-5等。
注:整数和浮点数在计算机内部存储的方式是不同的。
整数运算永远是精确的(包括除法),而浮点数运算则可能会有四舍五入的误差。
字符串是以单引号(‘ ’)或者双引号(“ ”)括起来的任意文本,例如 ‘qaz’,“wsx” 等。
(‘ ’)(“ ”)本身只是一种表示方式,不是字符串的一部分。因此,字符串‘abc’只有a,b,c这三个字符。如果(‘)本身也是一个字符,那就可以用(“ ”)括起来,例如:”I’m OK”包含的字符是(I)(’)(m)(空格)(O)(K)这六个字符。
如果字符里面既包含(’)又包含(“)的话,则可以使用转义字符(\)来标识,如:
'I\'m \"OK\"!'
表示的字符串内容是:
&&& print('I\'m \"OK\"!')
转义字符(\)可以转义很多字符,比如:
\n 表示换行
\t 表示制表符
字符(\)本身也要转义,所以(\)表示的字符就是(\)。
在Python的交互式命令终端用print()打印字符串查看:
&&& print('I\'m learning python. \nhjr ')
I'm learning python.
&&& print('\\\n\\')
如果字符串里面有很多字符需要转义,就需要加很多(\),为了简化,Python还允许用(r’ ‘)或(r“ ”)表示(’ ‘)或(“ ”)内部的字符串默认不转义。
&&& print('\\\t\\')
&&& print(r'\\\t\\')
&&& print(r"\\\t\\")
如果字符串内部有很多换行,用(\n)写在一行里面不好阅读,为了简化,Python允许用(“‘…’”)的格式表示多行内容。
注:三个单引号
&&& print('''yiyou
... yizheyouye
... python
... hadoop
... spark''')
yizheyouye
&&& print("""yiyou
... yizheyouye
... python
... hadoop
... good""")
yizheyouye
布尔值和布尔代数的表示完全一致,一个布尔值只有True和False两种值,也就是说要么True,要么False。在Python中,可以直接使用True或者False表示布尔值(注意大小写),也可以通过布尔运算计算出来:
布尔运算:and / or / not
and运算:与运算
只有所有都为True,and运算结果才是True:
&&& True and True
&&& True and False
&&& False and False
&&& 4&1 and 8&12
or运算:或运算
只要其中有一个为True,or运算结果就是True:
&&& True or True
&&& True or false
&&& False or False
&&& 8&3 or 9&1
not运算:非运算
它是一个单目运算符,把True变成False,False变成True:
&&& not True
&&& not False
&&& not 1&8
布尔值经常用在条件判断中,如:
if age &= 18:
print('adult')
print('teenager')
空值是Python里面一个特殊的值,用None表示。
注:None不能理解为0,因为0是有意义的,而None是一个特殊的空值。
计算机程序中,变量不仅可以是数字,也可以是任意数据类型
变量在程序中就是一个变量名表示,变量名必须是大小写英文/数字/和_下划线的组合,而且不能用数字开头。
变量a是一个整数
hjr_007="yiyou"
变量hjr_007是一个字符串
Answer=False
变量Answer是一个布尔值False
在Python中,等号(=)是赋值语句,可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量,如:
&&& a=8341
&&& print(a)
&&& a='ABC'
&&& print(a)
这种变量本身类型不固定的语言称之为动态语言,与之对应的是静态语言。
静态语言在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。比如:Java就是静态语言,赋值语句如下就会报错:
int a=8341;
和静态语言相比,动态语言更加灵活,就是这个原因。
注意:不能把赋值语句的等号等同于数学的等号。
析:X=X+3,在计算机程序中,赋值语句先计算右侧的表达式X+3,得到结果11,在赋值给X。由于X之前的值是8,重新赋值后,X的值变成11。
变量在计算机内存中的表示:
当我们写a=‘ABC’时,Python解释器做了两件事请:
1)在内存中创建了一个‘ABC’的字符串;
2)在内存中创建了一个名为a的变量,并把它指向‘ABC’。
也可以把一个变量a赋值给另一个变量b,这个操作实际上是把变量b指向变量a所指向的数据。
&&& a='ABC'
&&& a='XYZ'
&&& print(b)
1)执行a=‘ABC’,解释器创建了字符串‘ABC’和变量a,并把a指向‘ABC’。
2)执行b=a,解释器创建了变量b,并把b指向a指向的字符串’ABC‘。
3)执行a=’XYZ‘,解释器创建了字符串,并把a的指向改为’XYZ‘,但是b并没有更改。
所以,最后打印变量b的结果自然就是’ABC‘了。
常量就是不能变得变量,特殊的变量。比如常用的数学常数π就是一个常量。
在Python中,通常用全部大写的变量名表示常量:
但事实上,PI任然是一个变量,Python根本没有任何机制保证PI不会被改变,所以,用全部大写的变量名表示常量只是一个习惯上的用法。
附:整数的除法为什么是精确的
在Python中,有两种除法,一种除法是(/):
(/)除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数:
还有一种除法是(//),称为地板除,两个整数的除法任然是整数:
整数的地板除(//)永远是整数,即使是除不尽的情况。
要做精确的除法,使用(/)就可以。
无论整数做(//)除法还是取余数,结果永远是整数,所以说,整数运算结果永远是精确的。
&&& print(n)
&&& f=456.789
&&& print(f)
&&& s1='Hello World'
&&& print(s1)
Hello World
&&& s2='Hello,\'Adam\''
&&& print(s2)
Hello,'Adam'
&&& s3=r'Hello,"Bart"'
&&& print(s3)
Hello,"Bart"
&&& s4=r'''Hello,
... Roky!'''
&&& print(s4)
字符串和编码
字符串是一种数据类型,但是,字符串比较特殊的是还有一个编码问题。
因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理。
最早的计算机在设计时采用8个比特(bit)作为一个字节(byte),所以,一个字节能表示的最大的整数就是255(二进制=十进制255),如果要表示更大的整数,就必须用更多的字节。比如两个字节可以表示的最大整数是65535,4个字节可以表示的最大整数是。
由于计算机是美国人发明的,因此,最早只有127个字母被编码到计算机里,也就是大小写英文字母/数字和一些符号,这个编码表被称为ACSII编码,比如大写字母A的编码是65,小写字母z的编码是122。
我们要处理中文显然一个字节是不够的,至少得两个字节,而且还不能和ASCII编码冲突,所以,中国制定了GB2312编码,用来把中文编进去。
全世界有上百中语言,日本把日文编到Shift_JIS里,韩国把韩文编到Euc-kr里,各国有各国的标准,所以就会不可避免的出现冲突,结果就是,在多语言混合的文本中,显示出来就会有乱码。
因此,Unicode应运而生。
Unicode把所有的语言都统一到一套编码里面,这样就不会有乱码问题了。
Unicode标准也在不断发展,但是常用的是用两个字节表示一个字符(如果用到非常偏僻的字符,就需要4个字节)。现代操作系统和大多数编程语言都直接支持Unicode。
ASCII编码与Unicode编码的区别:
ASCII编码是一个字节,Unicode编码通常是两个字节。
字母(A)用ASCII编码是十进制的65,二进制的;
字符(0)用ASCII编码是十进制的48,二进制的;
(注意:字符‘0’和整数0是不同的)
汉字(中)已经超出了ASCII编码的范围,用Unicode编码是十进制的20013,二进制的01101。
如果把ASCII编码的A用Unicode编码,只需要在前面补0就可以了,故,A的Unicode编码是00001。
如果统一成Unicode编码,乱码问题从此消失了。但是,如果我们写的文本全部是英文的话,用Unicode编码比ASCII编码需要多一倍的存储空间,在存储和传输方面就十分不划算。
所以,本着节约的精神,又出现了把Unicode编码转换为“可变长编码”的UTF-8编码。
UTF-8编码把一个Unicode字符根据不同的数字大小编码成1-6个字节,常用的英文字母被编码成1个字节,汉字通常是3个字节,只有很生僻的字符才会被编码成4-6个字节。如果你要传输的文本包含大量英文字符,用UTF-8编码就能节省空间:
从上面的表格可以发现,UTF-8编码还有一个额外的好处,就是ASCII编码实际上可以被看成UTF-8编码的一部分,所以,大量支持ASCII编码的历史遗留软件可以在UTF-8编码下继续工作。
总结一下,计算机系统通用的字符编码工作方式:
在计算机内存中,统一使用Unicode编码,
当需要保存到硬盘或者需要传输的时候,就转换为UTF-8编码。
用记事本编辑的时候,从文件读取的UTF-8字符被转换为Unicode字符到内存里,编辑完成后,保存的时候再把Unicode字符转换为UTF-8字符保存到文件。
同理,浏览网页的时候,服务器会把动态生成的Unicode内容转换为UTF-8在传输到浏览器。
所以我们会看到很多网页的源码上会有类似的信息,表示网页使用的是UTF-8编码。
Python的字符串
在最新的Python3中,字符串是以Unicode编码的,所以,Python的字符串支持多国语言,比如:
&&& print('包含中文的string')
包含中文的string
对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符:
&&& ord('A')
&&& ord('中')
&&& chr(66)
&&& chr(25991)
如果知道字符的整数编码,还可以用十六进制写str:
&&& '\u4e2d\u6587'
两种写法完全等价。
由于Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节。如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes。
Python对bytes类型的数据用带b前缀的单引号或双引号表示:
注意区分‘ABC’和b’ABC’,前者是str,后者虽然内容显示的和前者一样,单bytes的每个字附都占用一个字节。
以Unicode表示的str通过encode()方法可以编码为指定的bytes,如下:
&&& 'ABC'.encode('ascii')
&&& '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
&&& '中文'.encode('ascii')
Traceback (most recent call last):
File "&stdin&", line 1, in &module&
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
纯英文的str可以用ASCII编码为bytes,内容是一样的,
含有中文的str可以用UTF-8编码为bytes。
含有中文的str无法用ASCII编码,因为中文编码的范围超过了ASCII编码的范围,Python会报错奥!
在bytes中,无法显示为ASCII字符的字节,用(\x##)显示。
反过来,如果我们从网络或磁盘上读取了字节流,那么读取到的数据就是bytes。要把bytes变为str,就需要用decode()方法:
&&& b'ABC'.decode('ascii')
&&& b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
要计算str包含多少个字符,可以用len()函数:
&&& len('ABC')
&&& len('中文')
len()函数计算的是str的字符数,如果换成bytes,len()函数就计算字节数:
&&& len(b'ABC')
&&& len(b'\xe4\xb8\xad\xe6\x96\x87')
&&& len('中文'.encode('utf-8'))
可见,一个中文字符经过UTF-8编码后通常会占用3个字节,而一个英文字符只占用1个字节。
在操作字符串时,我们经常遇到str和bytes的相互转换。为了避免乱码问题,应当始终坚持使用UTF-8编码对str和bytes进行转换。
由于Python源代码也是一个文本文件,所以,当你的源代码中包含中文的时候,在保存源代码的时候,就需要务必指定保存为UTF-8编码。当python解释器读取源代码时,为了让它按UTF-8编码读取,我们通常在文件开头写上这两行:
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
第一行注释是为了告诉Linux/OS X系统,这是一个Python可执行程序,Windows系统会忽略这个注释;
第二行注释是为了告诉Python解释器,按照UTF-8编码读取源代码,否则,你在源代码中写的中文输出可能会有乱码。
声明了UTF-8编码并不意味着你的(.py)文件就是UTF-8编码的,必须并且要确保文本编辑器正在使用UTF-8 without BOM编码。
如何输出格式化的字符串?
我们经常会输出类似“亲爱的×××你好!你××月的话费是××,余额是××”之类的字符串,而×××的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式。
在Python中,采用的格式化方式和C语言是一致的,用(%)实现,例如:
&&& 'Hello,%s' % 'Python'
'Hello,Python'
&&& 'Hi,%s,you have $%d.'%('hjr',999999)
'Hi,hjr,you have $999999.'
(%)运算符就是用来格式化字符串的。
在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个(%?)占位符,后面就跟几个变量或者值,顺序要对应好。
如果只有一个(%?),括号可以省略。
常见的占位符有:
十六进制整数
其中,格式化整数和浮点数还可以指定是否补0和整数与小数的位数:
&&& '%2d-%02d' % (3,1)
&&& '%.2f' % 3.
如果你还不太确定应该用什么,(%s)永远起作用,它会把任何数据类型转化为字符串:
&&& 'Age: %s. Gender: %s' % (25,True)
'Age: 25. Gender: True'
有些时候,字符串里面的%是一个普通字符怎么办?(百分比)这个时候就需要转义,用%%来表示%:
&&& 'growth rate %d %%' % 8
'growth rate 8 %'
小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点,并用字符串格式化显示出’xx.x%’,只保留小数点后1位:
&&& r=(s2-s1)/s1
&&& 'growth rate : %.1f %%' % r
'growth rate : 0.2 %'
使用 list 和 tuple
Python内置的一种数据类型是列表:list。
list是一种有序的集合,可以随时添加和删除其中的元素。
&&& classmates = ['yiyou','hjr','lr','hjj','lqq']
&&& classmates
['yiyou', 'hjr', 'lr', 'hjj', 'lqq']
变量classmates就是一个list。用len() 函数可以获得list元素的个数:
&&& len(classmates)
用索引来访问list中每一个位置的元素,注意:索引是从0开始的哟:
&&& classmates[0]
&&& classmates[1]
&&& classmates[2]
&&& classmates[3]
&&& classmates[4]
&&& classmates[5]
Traceback (most recent call last):
File "&stdin&", line 1, in &module&
IndexError: list index out of range
当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(classmates)-1。
如果要取最后一个元素,除了计算索引位置外,还可以用-1做索引,直接获取最后一个元素:
&&& classmates[-1]
以此类推,可以获取倒数第二个,倒数第三个等:
&&& classmates[-2]
&&& classmates[-3]
&&& classmates[-4]
&&& classmates[-5]
list是一个可变的有序列表,所以,可以往list中追加元素到末尾:
&&& classmates.append('fyh')
&&& classmates
['yiyou', 'hjr', 'lr', 'hjj', 'lqq', 'fyh']
也可以把元素插入到指定的位置,例如索引号为0的位置:
&&& classmates.insert(0,'yizheyouye')
&&& classmates
['yizheyouye', 'yiyou', 'hjr', 'lr', 'hjj', 'lqq']
要删除list末尾的元素,用pop()方法:
&&& classmates.pop()
&&& classmates
['yiyou', 'hjr', 'lr', 'hjj', 'lqq']
要删除指定位置的元素,用pop(i)方法,其中i是索引位置:
&&& classmates.pop(0)
'yizheyouye'
&&& classmates
['yiyou', 'hjr', 'lr', 'hjj', 'lqq']
要把某个元素替换成别的元素,可以直接赋值给对应的索引位置:
&&& classmates[4]='fyh'
&&& classmates
['yiyou', 'hjr', 'lr', 'hjj', 'fyh']
list里面的元素的数据类型也可以不同,比如:
&&& L=['Apple',8341,True]
['Apple', 8341, True]
list元素也可以是另一个list,例如:
&&& s=['python','scala',['spark','hadoop','flink'],'ruby','go']
['python', 'scala', ['spark', 'hadoop', 'flink'], 'ruby', 'go']
&&& len(s)
注意:s只有5个元素,其中s[2]又是一个list,如果拆开写就容易理解了:
&&& p=['spark','hadoop','flink']
&&& s=['python','scala',p,'ruby','go']
['python', 'scala', ['spark', 'hadoop', 'flink'], 'ruby', 'go']
想要拿到’spark‘,可以写p[0]或者s[2][0],因此,s可以看成一个二位数组,类似的还有三维/四维。。。数组,不过,很少用到。
如果一个list中一个元素都没有,就是一个空的list,它的长度为0:
&&& len(L)
另一种有序列表叫元祖:tuple
tuple和list非常类似,但是,tuple一旦初始化,就不能修改。
例如:同样是列出同学的名字:
&&& classmates=('hjr','lr','hjj','lqq')
现在,classmates这个tuple不能变了,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,我们可以正常使用classmates[0],classmates[-1],当然不能赋值给另外的元素。
不可变得tuple有什么意义呢?因为tuple不可变,代码更安全。如果可变,能用tuple代替list就尽量用tuple。
tuple陷阱:
当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来,比如:
&&& t=(1,2,3)
如果要定义一个空tuple,就可以写成():
但是,要定义一个只有一个元素的tuple,如果我们这么定义:
这么定义的就不是tuple,是1这个数字!
这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,在这种情况下,按小括号进行计算,计算结果自然是1咯。
所以,只有一个元素的tuple 定义 时必须加一个逗号(,),来消除歧义:
&&& t=(1,)
Python在 显示 只有一个元素的tuple时,也会加一个逗号(,),以免我们误解成数学计算意义上的括号。
最后,我们看一个“可变的”tuple:
&&& t=('a','b',['A','B'])
('a', 'b', ['A', 'B'])
&&& t[2][0]='X'
&&& t[2][1]='Y'
('a', 'b', ['X', 'Y'])
这个tuple定义的时候有三个元素,分别是’a‘,’b‘和一个list。
表面上看,tuple的元素确实变了,但实际变的不是tuple的元素,而是list的元素。
tuple一开始指向的list并没有改成别的list,所以,tuple所谓的“不变”是说,tuple的每一个元素,指向定义了以后就永远不变。
指向’a‘,就不能改变成’b‘,指向一个list,就不能改成指向其他对象,但指向的这个list本身是可以改变的!
了解了“指向不变”后,要创建一个内容也不变的tuple怎么做呢?
那就必须保证tuple的每一个元素本身也不能变。
&&& L=[['Apple','Google','Microsoft'],['Java','Python','Ruby','PHP'],['Adam','Bart','Lisa']]
[['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa']]
&&& print(L[0][0])
&&& print(L[1][1])
&&& print(L[2][2])
list和tuple是Python内置的有序集合,一个可变,一个不可变。我们根据需要选择使用。
计算机之所以能够做到很多自动化的任务,因为它可以自己做条件判断。
例如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用if语句实现:
if age &= 18:
print('your age is', age)
print('adult')
根据Python的缩进规则,如果if语句判断是True,就把缩进的两行print()语句执行了,否则,什么也不做。
也可以给if添加一个else语句,意思是,
如果if判断是False,不执行if语句内容,而是执行else语句内容:
if age &= 18:
print('your age is', age)
print('adult')
print('your age is', age)
print('teenager')
注意:不能少写冒号(:)
上面的判断还是很粗略的,完全可以用elif做更细致的判断:
if age &= 18:
print('adult')
elif age &= 6:
print('teenager')
print('kid')
elif是else if的缩写,完全可以有多个elif,所以if语句的完整形式就是:
if语句执行有个特点,它是从上往下判断,如果在某个判断上是True,把该判断对应的语句执行后,就会忽略掉剩下的elif和else语句。
所以,请测试并解释为什么下面的程序打印的是teenager:
if age &= 6:
print('teenager')
elif age &= 18:
print('adult')
print('kid')
满足第一个if后,执行完就跳出了判断语句。
if判断条件还可以简写,例如:
print('True')
只要x是非零数值/非空字符串/非空list等,就判断为True,否则为False。
我们有时候会用input()读取用户的输入,这样可以自己输入,程序运行的很有意思:
birth = input('birth:')
if birth & 2000:
print('00 qian')
print('00 hou')
这是因为input()返回的数据类型是str,而str不能直接和整数比较,必须先把str转换成整数。
Python提供了int()函数来完成这件事情:
s = input('birth:')
birth = int(s)
if birth & 2000:
print('00 qian')
print('00 hou')
再次运行,就可以得到正确的结果。但是,如果输入abc字符串呢?
又会得到一个错误信息:
int()函数发现一个字符串并不是合法的数字时就会报错,程序就退出了。
小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
低于18.5:过轻
18.5-25:正常
25-28:过重
28-32:肥胖
高于32:严重肥胖
height = 1.75
weight = 80.5
bmi = weight/(height*height)
if bmi & 18.5:
print('过轻')
elif bmi &= 18.5 and bmi & 25:
print('正常')
elif bmi &= 25 and bmi & 28:
print('过重')
elif bmi &= 28 and bmi & 32:
print('肥胖')
elif bmi & 32:
print('严重肥胖')
print('Exception !')
修改一下:
height = 1.75
weight = 80.5
bmi = weight/(height*height)
if bmi & 18.5:
print('过轻')
elif 18.5 &= bmi & 25:
print('正常')
elif 25 &= bmi & 28:
print('过重')
elif 28 &= bmi & 32:
print('肥胖')
elif bmi & 32:
print('严重肥胖')
print('Exception !')
计算1+2+3,我们可以直接写表达式:
要计算1+2+3+4+…+10,勉强也能写出来。
但是,要计算1+2+3+…+10000,直接写表达式是不明智的。
为了让计算机能计算成千上万次的重复运算,我们就需要循环语句。
Python的循环有两种,一种是for…in循环,依次把list或者tuple中的每一个元素迭代出来,如下:
names = ['hjr','lr','hjj','lqq']
for name in names:
print(name)
执行这段代码,会依次打印names中的每一个元素:
所以,for x in …循环就是把每个元素带入变量x,然后执行行缩进块的语句。
在比如我们想计算1-10的整数之和,我们可以用一个sum变量做累加:
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
<span class="h
感谢关注 Ithao123Python频道,是专门为互联网人打造的学习交流平台,全面满足互联网人工作与学习需求,更多互联网资讯尽在 IThao123!
Laravel是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。
Hadoop是一个由Apache基金会所开发的分布式系统基础架构。
用户可以在不了解分布式底层细节的情况下,开发分布式程序。充分利用集群的威力进行高速运算和存储。
Hadoop实现了一个分布式文件系统(Hadoop Distributed File System),简称HDFS。HDFS有高容错性的特点,并且设计用来部署在低廉的(low-cost)硬件上;而且它提供高吞吐量(high throughput)来访问应用程序的数据,适合那些有着超大数据集(large data set)的应用程序。HDFS放宽了(relax)POSIX的要求,可以以流的形式访问(streaming access)文件系统中的数据。
Hadoop的框架最核心的设计就是:HDFS和MapReduce。HDFS为海量的数据提供了存储,则MapReduce为海量的数据提供了计算。
产品设计是互联网产品经理的核心能力,一个好的产品经理一定在产品设计方面有扎实的功底,本专题将从互联网产品设计的几个方面谈谈产品设计
PHP(外文名:PHP: Hypertext Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言。语法吸收了C语言、Java和Perl的特点,利于学习,使用广泛,主要适用于Web开发领域。PHP 独特的语法混合了C、Java、Perl以及PHP自创的语法。它可以比CGI或者Perl更快速地执行动态网页。用PHP做出的动态页面与其他的编程语言相比,PHP是将程序嵌入到HTML(标准通用标记语言下的一个应用)文档中去执行,执行效率比完全生成HTML标记的CGI要高许多;PHP还可以执行编译后代码,编译可以达到加密和优化代码运行,使代码运行更快。
IThao123周刊

我要回帖

更多关于 python 循环累加 的文章

 

随机推荐