Basic data types 1-3 Python

Python is no need to declare variables. Each variable must be assigned before use variable assignment after the variable will be created.

In Python, a variable is a variable, it is not the type we call "type" is the type of objects in memory within the meaning of the variables.

Equal sign (=) is used to assign values ​​to variables.

Equal sign (=) operator is a left variable name, an equal sign (=) operator is the right value stored in the variable. E.g:

#!/usr/bin/python3
 
counter = 100          # 整型变量
miles   = 1000.0       # 浮点型变量
name    = "runoob"     # 字符串
 
print (counter)
print (miles)
print (name)

The implementation of the above program will output the following results:

100
1000.0
runoob

Multiple variable assignment

Python allows you to assign multiple variables simultaneously. E.g:

a = b = c = 1

Examples of the above, an object to create an integer, a value of 1, from the rear forward assignment, three variables are given the same value.

You can also specify multiple variables into multiple objects. E.g:

a, b, c = 1, 2, "runoob"

The above example, two integer objects 1 and 2 is allocated to the variable a and B, string objects "runoob" assigned to the variable c.


Standard data types

Python3 There are six standard data types:

  • Number (Digital)
  • String (String)
  • List (list)
  • Tuple (tuple)
  • Set (collection)
  • Dictionary (dictionary)

Python3 of six standard data types:

  • Immutable data (3): Number The (digital), String (String), Tuple (tuple);
  • Variable data (3): List (list), Dictionary (dictionary), Set (collection).

Number (Digital)

Python3 support  int, float, bool, complex (plural) .

In Python 3, there is only one integer type int, expressed as a long integer, no python2 of Long.

Like most languages, numeric types of assignments and calculations are very intuitive.

Built-in type () function can be used to query object type variable points.

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

Isinstance also be used to determine:

>>>a = 111
>>> isinstance(a, int)
True
>>>

The difference is that isinstance and type:

  • type () does not think that is a subclass of the parent type.
  • isinstance () will be considered sub-class is a parent class type.
>>> class A:
...     pass
... 
>>> class B(A):
...     pass
... 
>>> isinstance(A(), A)
True
>>> type(A()) == A 
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False

Note: In Python2 is no Boolean type, which represents the number 0 with False, represented by 1. True. To Python3 in the True and False is defined as a keyword, but the value 0 or 1 and, they may be digital addition.

When you specify a value, Number object is created:

var1 = 1
var2 = 10

You can also use the del statement to delete some object reference.

del statement syntax is:

del var1[,var2[,var3[....,varN]]]

You can delete individual or multiple objects by using the del statement. E.g:

del var
del var_a, var_b

Numerical computation

>>>5 + 4  # 加法
9
>>> 4.3 - 2 # 减法
2.3
>>> 3 * 7  # 乘法
21
>>> 2 / 4  # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余 
2
>>> 2 ** 5 # 乘方
32

note:

  • 1, Python may for multiple variable assignments, such as a, b = 1, 2.
  • 2, a variable may be directed by assigning different types of objects.
  • 3, comprises two division values ​​operators: / returns a floating point number, // returns an integer.
  • 4, upon mixing calculations, Python integer will be converted into floating-point numbers.

Examples of value type

int float complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3e + 18 .876j
-0490 -90. -.6545 + 0J
-0x260 -32.54e100 3e + 26J
0x69 70.2E-12 4.53e-7j

Python also supports complex, the complex composed of a real part and an imaginary number part, may be used a + bj, or Complex (a, b) indicates, the real part and the imaginary part b is a floating-point


String (String)

Python in single quotes' or double quotes "quotes, while the backslash \ escape special characters.

Taken string syntax is as follows:

Variable [head index: Tail subscript]

Index value to the starting value 0, -1 from the end of the start position.

Plus sign + is string connector, the asterisk * indicates copy the current string, immediately following the number of times the digital copy. Examples are as follows:

str = 'Runoob'
 
print (str)          # 输出字符串
print (str[0:-1])    # 输出第一个到倒数第二个的所有字符
print (str[0])       # 输出字符串第一个字符
print (str[2:5])     # 输出从第三个开始到第五个的字符
print (str[2:])      # 输出从第三个开始的后的所有字符
print (str * 2)      # 输出字符串两次
print (str + "TEST") # 连接字符串

The implementation of the above program will output the following results:

Runoob
Runoo
R
noo
noob
RunoobRunoob
RunoobTEST

Python uses the backslash (\) escape special characters if you do not want the backslash escape occurs, you can add a r in front of the string that represents the original string:

>>> print('Ru\noob')
Ru
oob
>>> print(r'Ru\noob')
Ru\noob
>>> 

Further, a backslash (\) may be used as line continuation character, indicating that the next line is a continuation line. You can also use  "" "..." ""  or  '' '...' ''  span multiple lines.

Note that, Python no separate character type is a character string of length 1.

>>>word = 'Python'
>>> print(word[0], word[5])
P n
>>> print(word[-1], word[-6])
n P

The difference is that the C string, Python strings can not be changed. Assigning a value to an index location, such as word [0] = 'm' will cause an error. 

note:

  • 1, can be used to escape the backslash, backslash escapes allow the use of r can not occur.
  • 2, the + operator strings can be connected together, with the * operator repeats.
  • 3, Python strings have two indexing methods, starting with 0 from left to right, right to left to begin -1.
  • 4, the string can not be changed in Python.

List (list)

List (list) is the most frequently used Python data types.

You can complete the list data structure to achieve most of the collection class. Type elements in the list may not be identical, which supports numbers, strings may even contain a list (called nesting).

List is written between the [] brackets, comma-separated list of elements.

And like strings, and indexing the list can also be taken after the list is taken returns a new list containing required elements.

List intercepted syntax is as follows:

Variable [head index: Tail subscript]

Index value to the starting value 0, -1 from the end of the start position.

+ Plus operator is a list of connections, the asterisk * is repeated. Following examples:

Examples

 
list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ]
tinylist = [123, 'runoob']
 
print (list)            # 输出完整列表
print (list[0])         # 输出列表第一个元素
print (list[1:3])       # 从第二个开始输出到第三个元素
print (list[2:])        # 输出从第三个元素开始的所有元素
print (tinylist * 2)    # 输出两次列表
print (list + tinylist) # 连接列表

Examples of the above output:

['abcd', 786, 2.23, 'runoob', 70.2]
abcd
[786, 2.23]
[2.23, 'runoob', 70.2]
[123, 'runoob', 123, 'runoob']
['abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob']

And Python strings are not the same, the elements in the list can be changed:

>>>a = [1, 2, 3, 4, 5, 6]
>>> a[0] = 9
>>> a[2:5] = [13, 14, 15]
>>> a
[9, 2, 13, 14, 15, 6]
>>> a[2:5] = []   # 将对应的元素值设置为 [] 
>>> a
[9, 2, 6]

List built there are many ways, such as append (), pop (), etc., which will be mentioned later.

note:

  • 1, List written between square brackets, elements separated by commas.
  • 2, and the same string, list can be indexed and sliced.
  • 3, List can be spliced ​​using the + operator.
  • 4, List the elements can be changed.

Python 列表截取可以接收第三个参数,参数作用是截取的步长,以下实例在索引 1 到索引 4 的位置并设置为步长为 2(间隔一个位置)来截取字符串:

如果第三个参数为负数表示逆向读取,以下实例用于翻转字符串:

def reverseWords(input): 
      
    # 通过空格将字符串分隔符,把各个单词分隔为列表
    inputWords = input.split(" ") 
  
    # 翻转字符串
    # 假设列表 list = [1,2,3,4],  
    # list[0]=1, list[1]=2 ,而 -1 表示最后一个元素 list[-1]=4 ( 与 list[3]=4 一样) 
    # inputWords[-1::-1] 有三个参数
    # 第一个参数 -1 表示最后一个元素
    # 第二个参数为空,表示移动到列表末尾
    # 第三个参数为步长,-1 表示逆向
    inputWords=inputWords[-1::-1] 
  
    # 重新组合字符串
    output = ' '.join(inputWords) 
      
    return output 
  
if __name__ == "__main__": 
    input = 'I like runoob'
    rw = reverseWords(input) 
    print(rw)

输出结果为:

runoob like I

Tuple(元组)

元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号 () 里,元素之间用逗号隔开。

元组中的元素类型也可以不相同:

tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2  )
tinytuple = (123, 'runoob')
 
print (tuple)             # 输出完整元组
print (tuple[0])          # 输出元组的第一个元素
print (tuple[1:3])        # 输出从第二个元素开始到第三个元素
print (tuple[2:])         # 输出从第三个元素开始的所有元素
print (tinytuple * 2)     # 输出两次元组
print (tuple + tinytuple) # 连接元组

以上实例输出结果:

('abcd', 786, 2.23, 'runoob', 70.2)
abcd
(786, 2.23)
(2.23, 'runoob', 70.2)
(123, 'runoob', 123, 'runoob')
('abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob')

元组与字符串类似,可以被索引且下标索引从0开始,-1 为从末尾开始的位置。也可以进行截取(看上面,这里不再赘述)。

其实,可以把字符串看作一种特殊的元组。

>>>tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup[0] = 11  # 修改元组元素的操作是非法的
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>

虽然tuple的元素不可改变,但它可以包含可变的对象,比如list列表。

构造包含 0 个或 1 个元素的元组比较特殊,所以有一些额外的语法规则:

tup1 = ()    # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号

string、list 和 tuple 都属于 sequence(序列)。

注意:

  • 1、与字符串一样,元组的元素不能修改。
  • 2、元组也可以被索引和切片,方法一样。
  • 3、注意构造包含 0 或 1 个元素的元组的特殊语法规则。
  • 4、元组也可以使用+操作符进行拼接。

Set(集合)

集合(set)是由一个或数个形态各异的大小整体组成的,构成集合的事物或对象称作元素或是成员。

基本功能是进行成员关系测试和删除重复元素。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

创建格式:

parame = {value01,value02,...}
或者
set(value)
#!/usr/bin/python3
 
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
 
print(student)   # 输出集合,重复的元素被自动去掉
 
# 成员测试
if 'Rose' in student :
    print('Rose 在集合中')
else :
    print('Rose 不在集合中')
 
 
# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')
 
print(a)
 
print(a - b)     # a 和 b 的差集
 
print(a | b)     # a 和 b 的并集
 
print(a & b)     # a 和 b 的交集
 
print(a ^ b)     # a 和 b 中不同时存在的元素

以上实例输出结果:

{'Mary', 'Jim', 'Rose', 'Jack', 'Tom'}
Rose 在集合中
{'b', 'a', 'c', 'r', 'd'}
{'b', 'd', 'r'}
{'l', 'r', 'a', 'c', 'z', 'm', 'b', 'd'}
{'a', 'c'}
{'l', 'r', 'z', 'm', 'b', 'd'}

Dictionary(字典)

字典(dictionary)是Python中另一个非常有用的内置数据类型。

列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

字典是一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。

键(key)必须使用不可变类型。

在同一个字典中,键(key)必须是唯一的。

#!/usr/bin/python3
 
dict = {}
dict['one'] = "1 - 菜鸟教程"
dict[2]     = "2 - 菜鸟工具"
 
tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'}
 
 
print (dict['one'])       # 输出键为 'one' 的值
print (dict[2])           # 输出键为 2 的值
print (tinydict)          # 输出完整的字典
print (tinydict.keys())   # 输出所有键
print (tinydict.values()) # 输出所有值

以上实例输出结果:

1 - 菜鸟教程
2 - 菜鸟工具
{'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
dict_keys(['name', 'code', 'site'])
dict_values(['runoob', 1, 'www.runoob.com'])

构造函数 dict() 可以直接从键值对序列中构建字典如下:

>>>dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])
{'Taobao': 3, 'Runoob': 1, 'Google': 2}
 
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
 
>>> dict(Runoob=1, Google=2, Taobao=3)
{'Runoob': 1, 'Google': 2, 'Taobao': 3}

另外,字典类型也有一些内置的函数,例如clear()、keys()、values()等。

注意:

  • 1、字典是一种映射类型,它的元素是键值对。
  • 2、字典的关键字必须为不可变类型,且不能重复。
  • 3、创建空字典使用 { }

Python数据类型转换

有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。

以下几个内置的函数可以执行数据类型之间的转换。这些函数返回一个新的对象,表示转换的值。

函数 描述

int(x [,base])

将x转换为一个整数

float(x)

将x转换到一个浮点数

complex(real [,imag])

创建一个复数

str(x)

将对象 x 转换为字符串

repr(x)

将对象 x 转换为表达式字符串

eval(str)

用来计算在字符串中的有效Python表达式,并返回一个对象

tuple(s)

将序列 s 转换为一个元组

list(s)

将序列 s 转换为一个列表

set(s)

转换为可变集合

dict(d)

创建一个字典。d 必须是一个序列 (key,value)元组。

frozenset(s)

转换为不可变集合

chr(x)

将一个整数转换为一个字符

ord(x)

将一个字符转换为它的整数值

hex(x)

将一个整数转换为一个十六进制字符串

oct(x)

将一个整数转换为一个八进制字符串

Guess you like

Origin blog.csdn.net/u012717715/article/details/91807026