Home  >  Article  >  Backend Development  >  PYTHON blog records

PYTHON blog records

巴扎黑
巴扎黑Original
2017-06-23 14:47:191317browse

1. Python#UnicodeString

Characters There is also an encoding issue with strings.

#Because computers can only process numbers, if you want to process text, you must first convert the text into numbers before processing. The earliest computers were designed using 8 bits (bit) as a byte (byte) , so the largest integer that can be represented by one byte is 255 (binary 11111111=decimal 255 ), 0 - 255 is used to represent uppercase and lowercase English letters, numbers and some symbols. This encoding table is called ASCII encoding, for example, the encoding for uppercase letters A is 65, and for lowercase letters z The encoding of is 122.

#If you want to represent Chinese, obviously one byte is not enough, at least two bytes are needed. And it cannot conflict with the ASCII encoding. Therefore, China has formulated the GB2312 encoding to encode Chinese characters.

Similarly, other languages ​​such as Japanese and Korean also have this problem. In order to unify the encoding of all text, Unicode came into being. UnicodeUnify all languages ​​into one set of encodings, so that there will no longer be garbled code problems.

UnicodeUsually two bytes are used to represent a character. The original English encoding changed from a single byte To become double-byte, just fill in the high byte as 0.

Because the birth of Python is faster than Unicode The standard was released even earlier, so the earliest Python only supports ASCII encoding, ordinary strings'ABC' is encoded internally in Python#ASCII.

Python later added support for Unicode, and the string represented by Unicode is u'...' represents, for example:

print u'中文'

UnicodeString Except for the extra u , it is no different from an ordinary string. The escape characters and multi-line representation are still valid:


print u'中文\n日文\n韩文'

Multiple lines:

u'''第一行
第二行'''

raw+Multiple lines:

ur'''Python的Unicode字符串支持"中文",
"日文",
"韩文"等多种语言'''

If the Chinese string is in UnicodeDecodeError is encountered in the Python environment. This is because there is a problem with the format of the .py file. You can add a comment

# -*- coding: utf-8 -*-

on the first line to tell the Python interpreter to use UTF-8Encoding reads source code. Then use Notepad++ to save as ... and select the UTF-8 format save.

2. PythonIntegers and floating-point numbers

Python supports direct mixed arithmetic operations on integers and floating-point numbers. The operation rules are completely consistent with the four arithmetic operations rules in mathematics.

Basic operations:

1 + 2 + 3   # ==> 6
4 * 5 - 6   # ==> 14
7.5 / 8 + 2.1   # ==> 3.0375
(1 + 2) * 3    # ==> 9
(2.2 + 3.3) / (1.5 * (9 - 0.3))    # ==> 0.42145593869731807


Using parentheses can increase the priority, which is exactly the same as mathematical operations. Note that only parentheses can be used, but parentheses can be nested in many levels: ## The difference between

# and mathematical operations is that the result of Python's integer operation is still an integer, and the result of floating-point operation is still a floating-point number:

1 + 2    # ==> 整数 3
1.0 + 2.0    # ==> 浮点

But the result of the mixed operation of integers and floating point numbers becomes floating point numbers:

1 + 2.0    # ==> 浮点数 3.0

为什么要区分整数运算和浮点数运算呢?这是因为整数运算的结果永远是精确的,而浮点数运算的结果不一定精确,因为计算机内存再大,也无法精确表示出无限循环小数,比如 0.1 换成二进制表示就是无限循环小数。

 

那整数的除法运算遇到除不尽的时候,结果难道不是浮点数吗?

11 / 4    # ==> 2


令很多初学者惊讶的是,Python的整数除法,即使除不尽,结果仍然是整数,余数直接被扔掉。不过,Python提供了一个求余的运算 % 可以计算余数:

11 % 4    # ==> 3

如果我们要计算 11 / 4 的精确结果,按照“整数和浮点数混合运算的结果是浮点数”的法则,把两个数中的一个变成浮点数再运算就没问题了:

11.0 / 4    # ==> 2.75

三、Python中布尔类型

 

#与运算
True and True   # ==> True
True and False   # ==> False
False and True   # ==> False
False and False   # ==> False

#或运算
True or True   # ==> True
True or False   # ==> True
False or True   # ==> True
False or False   # ==> False

#非运算
not True   # ==> False
not False   # ==> True

a = True
print a and 'a=T' or 'a=F'
#计算结果不是布尔类型,而是字符串 'a=T',这是为什么呢?

#因为Python把0、空字符串''和None看成 False,其他数值和非空字符串都看成 True,所以:

True and 'a=T' #计算结果是 'a=T'
#继续计算 'a=T' or 'a=F' 计算结果还是 'a=T'

要解释上述结果,又涉及到 and or 运算的一条重要法则:短路计算。

1. 在计算 a and b 时,如果 a False,则根据与运算法则,整个结果必定为 False,因此返回 a;如果 a True,则整个计算结果必定取决与 b,因此返回 b

 

2. 在计算 a or b 时,如果 a True,则根据或运算法则,整个计算结果必定为 True,因此返回 a;如果 a False,则整个计算结果必定取决于 b,因此返回 b

 

所以Python解释器在做布尔运算时,只要能提前确定计算结果,它就不会往后算了,直接返回结果。

 

 

 

 

 

 

四、Python创建list

Python内置的一种数据类型是列表:listlist是一种有序的集合,可以随时添加和删除其中的元素。

 

比如,列出班里所有同学的名字,就可以用一个list表示:

>>> ['Michael', 'Bob', 'Tracy']
['Michael', 'Bob', 'Tracy']

list是数学意义上的有序集合,也就是说,list中的元素是按照顺序排列的。

 

构造list非常简单,按照上面的代码,直接用 [ ] list的所有元素都括起来,就是一个list对象。通常,我们会把list赋值给一个变量,这样,就可以通过变量来引用list

classmates = ['Michael', 'Bob', 'Tracy']
classmates # 打印classmates变量的内容
>>>['Michael', 'Bob', 'Tracy']

由于Python是动态语言,所以list中包含的元素并不要求都必须是同一种数据类型,我们完全可以在list中包含各种数据:

L = ['Michael', 100, True]

一个元素也没有的list,就是空list

empty_list = []
#打印成绩表
L = ['adam', 95.5,'lisa', 85,'bart', 59]
print L

 

五、Python按照索引访问list


由于list是一个有序集合,所以,我们可以用一个list按分数从高到低表示出班里的3个同学:

L = ['Adam', 'Lisa', 'Bart']

那我们如何从list中获取指定第 N 名的同学呢?方法是通过索引来获取list中的指定元素。

 

需要特别注意的是,索引从 0 开始,也就是说,第一个元素的索引是0,第二个元素的索引是1,以此类推。

 

因此,要打印第一名同学的名字,用 L[0]:

但使用索引时,千万注意不要越界,所以没有L[3]

六、Python之倒序访问list

L = ['Adam', 'Lisa', 'Bart']
print L[-1]
>>>Bart

 


七、Pythonlist添加新元素

L = ['Adam', 'Lisa', 'Bart']

 

把新同学Paul添加到现有的 list

7.1append()

第一个办法是用 list append() 方法,把新同学追加到 list 的末尾:

L = ['Adam', 'Lisa', 'Bart']
L.append('Paul')
print L
>>> ['Adam', 'Lisa', 'Bart', 'Paul']

append()总是把新的元素添加到 list 的尾部。

 

7.2insert()

  listinsert()方法,它接受两个参数,第一个参数是索引号,第二个参数是待添加的新元素:

L = ['Adam', 'Lisa', 'Bart']
L.insert(0, 'Paul')
print L
>>>['Paul', 'Adam', 'Lisa', 'Bart']

L.insert(0, 'Paul') 的意思是,'Paul'将被添加到索引为 0 的位置上(也就是第一个),而原来索引为 0 Adam同学,以及后面的所有同学,都自动向后移动一位。

 

八、Python从list删除元素

 L = ['Adam', 'Lisa', 'Bart', 'Paul']
L.pop()
>>>'Paul'
 print L
>>>['Adam', 'Lisa', 'Bart']

pop()默认删除最后一个,当让也可以指定

L = ['Adam', 'Lisa', 'Paul', 'Bart']
L.pop(2)
>>>'Paul'
print L
>>> ['Adam', 'Lisa', 'Bart']


九、PythonList中替换元素

L = ['Adam', 'Lisa', 'Paul', 'Bart']
L[2] = 'Paul' #或者 L[-1] = 'Paul'
print L
>>> L = ['Adam', 'Lisa', 'Paul']

十、Python之创建tuple

tuple是另一种有序的列表,中文翻译为“ 元组 ”。tuple list 非常类似,但是,tuple一旦创建完毕,就不能修改了。

 

同样是表示班里同学的名称,用tuple表示如下:

t = ('Adam', 'Lisa', 'Bart')

  

创建tuple和创建list唯一不同之处是用( )替代了[ ]

 

现在,这个 t 就不能改变了,tuple没有 append()方法,也没有insert()pop()方法。所以,新同学没法直接往 tuple 中添加,老同学想退出 tuple 也不行。

 

获取 tuple 元素的方式和 list 是一模一样的,我们可以正常使用 t[0]t[-1]等索引方式访问元素,但是不能赋值成别的元素

 

十一、Python之创建单元素tuple

tuplelist一样,可以包含 0 个、1个和任意多个元素。

 

包含多个元素的 tuple,前面我们已经创建过了。

 

包含 0 个元素的 tuple,也就是空tuple,直接用 ()表示:

t = ()
print t
>>>()

  

 t = (1)
print t
>>> 1
#???这是为什么,因为()既可以表示tuple,又可以作为括号表示运算时的优先级,结果 (1) 被Python解释器计算出结果 1,导致我们得到的不是tuple,而是整数 1。

  

正是因为用()定义单元素的tuple有歧义,所以 Python 规定,单元素 tuple 要多加一个逗号“,”,这样就避免了歧义:

t = (1,)
print t
>>>(1,)

Python在打印单元素tuple时,也自动添加了一个“,”,为了更明确地告诉你这是一个tuple

 

多元素 tuple 加不加这个额外的“,”效果是一样的。

 

 


十二、Python之“可变”的tuple

 

t = ('a', 'b', ['A', 'B'])
#t = ('a', 'b', ('A', 'B'))的话就是不可变的

注意到 t 3 个元素:'a''b'和一个list['A', 'B']list作为一个整体是tuple的第3个元素。list对象可以通过 t[2] 拿到:

 L = t[2]
L[0] = 'X'
L[1] = 'Y'
print t
>>>('a', 'b', ['X', 'Y'])

 

The above is the detailed content of PYTHON blog records. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn