Python-Basic data types in Python language (lists and dictionaries)

PyCharm tips

#_*_ coding;uft-8 _*_

'''
PyCharm常用的「快捷键」:

1.shift + enter     :快速换行
2.ctrl + p          :代码提示
3.ctrl + alt +space :代码提示

PyCharm界面颜色设置 : File | Settings | Appearance & Behavior | Appearance|Darcula(暗色)
'''

Python3 basic data types

Variables in Python "do not need to be declared".
Each variable must be "assigned" before being used, and the variable will be created after the variable is assigned.
In Python, a variable is a variable. It has no type. What we call "type" is the type of the object in the memory that the variable refers to.

The equal sign (=) is used to assign values ​​to variables.
The left side of the equal sign (=) operator is a variable name , and the right side of the equal sign (=) operator is the value stored in the variable .

Standard data type

There are six standard data types in Python3:

  • Number
  • String
  • List
  • Tuple (tuple)
  • Set
  • Dictionary

Among the six standard data types of Python3:

  • Immutable data (3) : Number (number), String (string), Tuple (tuple);
  • Variable data (3) : List (List)、Dictionary(dictionary), Set.

Number

Python3 supports int , float , bool , complex (complex numbers).

Python also supports complex numbers. A complex number is composed of a real part and an imaginary part, which can be represented by a + bj, or complex(a,b). The real part a and imaginary part b of a complex number are both floating-point types.
Insert picture description here

In Python 3, there is only one integer type int, which is represented as a long integer, and there is no Long in python2.

Like most languages, the assignment and calculation of numeric types are very intuitive.

The built-in type() function can be used to query the object type pointed to by the variable.

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))

When you specify a value, the Number object is created:

var1 = 1
var2 = 10

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

The syntax of the del statement is:

del var
del var_a, var_b

Numerical operations

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

List

The list consists of a series of elements arranged in a specific order . You can create a list that contains all the letters of the alphabet , numbers 0-9, or the names of all family members; you can also add anything to the list, and there can be no relationship between the elements in the period. Since lists usually contain multiple elements, it is a good idea to give the list a name that represents a plural number (such as letters, digits, or names).

In Python, square brackets ( [] ) are used to denote lists, and Duhao is used to separate the elements in the period. Here is an example of a simple list of several bicycles:

bicycles.py

bicycles = [ 'trek','cannondale','redline','specialized']

print(bicycles)

#注释
'''
注释
'''

Example 2:

list = ['abcd',3,17.2,] #字符串、数字

print(list)

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

The list can complete the data structure realization of most collections. The types of elements in the list can be different, it supports numbers , strings and even lists (so-called nesting) .

List is written in square brackets [] between, by a comma -separated list of elements.

Like strings, lists can also be indexed and intercepted . After the list is intercepted, a new list containing the required elements is returned.

The syntax format of list interception is as follows:

变量[头下标:尾下标]

E.g:

list[2:5]

The index value starts with 0 , and -1 is the starting position from the end.
Insert picture description here

The plus sign + is the list concatenation operator, and the asterisk * is the repeated operation. Examples are as follows:


list = ['abcd',3,17.2,'e']
tinylist = [123,'runoob']

print("list=",end="")
print(list)                         # 输出完整列表
print("tinylist=",end="")
print(tinylist)
print("list + tinylist=",end="")
print(list + tinylist)              # 加号"+" 连接列表
print(list * 2)                     # 输出两次列表
print(list[0])                      # 输出列表的第一个元素
print(list[1:3])                    # 从第二个元素开始输出到第三个元素(不包含第三个元素)
print(list[1:])                     # 输出从第二个元素开始的所有元素

Set

A set is composed of one or several wholes of different sizes. The things or objects that make up the set are called elements or members.

The basic function is to test membership and delete duplicate elements.

Braces {} may be used or a set () function creates a set of note: create a null set together must set () instead of {}, because {} is used to create an empty dictionary.

Create format:

parame = {value01,value02,...}

or

set(value)

Examples:

#!/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 中不同时存在的元素

Dictionary

Dictionary (dictionary) is another very useful built-in data type in Python.

A list is an ordered collection of objects , and a dictionary is an unordered collection of objects . The difference between the two is that the elements in the dictionary are accessed through keys, not offsets.

A dictionary mapping type, with dictionaries {} identifier, which is an unordered key (key): Value (value) set.

The key must use an immutable type.

In the same dictionary, the key must be unique.


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()) # 输出所有值



Python data type conversion

Sometimes, we need to convert the built-in type of the data. To convert the data type, you only need to use the data type as the function name.

The following built-in functions can perform conversion between data types. These functions return a new object that represents the converted value.
Insert picture description here


Reference


Exercise (20200512):

#_*_ coding;uft-8 _*_

'''
PyCharm常用的「快捷键」:

1.shift + enter     :快速换行
2.ctrl + p          :代码提示
3.ctrl + alt +space :代码提示

PyCharm界面颜色设置 : File | Settings | Appearance & Behavior | Appearance|Darcula(暗色)
'''



#********************************************************************01
# print
'''
print默认输出是换行的,如果要实现不换行需要在变量末尾加上「end=""」 
'''
a = "Hello , World!"
b = "Hello ,Python!"
print(a,end="")
print(b,end="")

#********************************************************************02
# 注释
#Python 中单行注释以#开头,实例如下:
#第一个注释
print("Hello,Python!")#第二个注释

#第一个注释
#第二个注释

'''
第三注释
第四注释
'''

"""
第五注释
第六注释
"""

print("Hello,Python!")

#********************************************************************03
#行与缩进
'''
Python最具特色的就是使用「缩进」来表示代码块,不需要使用大括号{ }。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进「空格数」

'''

if True:
    print("True")
else:
    print("False")



#********************************************************************04
#多行语句
'''
Python通常是一行写完一条语句,但是如果语句很长,我们可以使用「反斜杠\」来实现多行语句
'''
item_one = 1
item_two = 2
item_three = 3
total = item_one + \
        item_two + \
        item_three
counter = item_one + item_two + item_three

print(total)
print(counter)



#********************************************************************05
#Python3 基本数据类型

'''
Python中的变量「不需要声明」。「」
每个变量在使用前都必须「赋值」,变量赋值以后该变量才会被创建。
在Python中,变量就是变量,它没有类型,我们所说的"类型"是变量所指的内存中对象的类型。

等号(=)用来给变量赋值。
等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值。
'''
#多个变量赋值
#********************************************************************06
#标准数据类型
'''
Python3中有六个标准的数据类型
    Number(数字)
    String(字符串)
    List(列表)
    Tuple(元组)
    Set(集合)
    Dictionary(字典)
'''
print("****************************Number 数字****************************")
print()#自动换行

a_int = 100             #整型变量
a_float = 100.0         #浮点型变量
a_string =  "runoob"    #字符串
a_complex = 4+3j        #复数
a_bool   = True         #布尔

print(a_int)
print(a_float)
print(a_string)
print(a_complex)
print(a_bool)

#内置的 type() 函数可以用来查询变量所指的对象类型。type()函数查看数据类型
print(type(a_int),type(a_float),type(a_string),type(a_complex),type(a_bool))

#数值运算

print("数值运算:",end="")

jiafa  =  4 + 5              #加法
jianfa =  4.3 - 2            #减法
chengfa = 3 * 7              #乘法
chufa   = 2 / 4              #除法,得到一个浮点数
chufa2  = 2 // 4             #除法,得到一个整数
quyu    = 17 % 3             #取余
chengfang = 2 ** 5           #乘方
print(jiafa,jianfa,chengfa,chufa,chufa2,quyu,chengfang)

print()#自动换行
print("****************************L i s t 列 表****************************")
print()#自动换行


list = ['abcd',3,17.2,'e']
tinylist = [123,'runoob']

print("list=",end="")
print(list)                         # 输出完整列表
print("tinylist=",end="")
print(tinylist)
print("list + tinylist=",end="")
print(list + tinylist)              # 加号"+" 连接列表
print(list[0])                      # 输出列表的第一个元素
print(list[1:3])                    # 从第二个元素开始输出到第三个元素(不包含第三个元素)
print(list[1:])                     # 输出从第二个元素开始的所有元素
print(list * 2)                     # 输出两次列表



print("****************************S e t 集 合****************************")
print()#自动换行

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 中不同时存在的元素

print("****************************Dictionary 字 典****************************")
print()#自动换行


dict = {
    
    }
dict['one'] = "1 - 菜鸟教程"
dict[2]     = "2 - 菜鸟工具"

tinydict = {
    
    'name': 'runoob','code':1, 'site': 'runoob.com'}


print (dict['one'])       # 输出键为 'one' 的值
print (dict[2])           # 输出键为 2 的值
print (tinydict)          # 输出完整的字典
print (tinydict.keys())   # 输出所有键
print (tinydict.values()) # 输出所有值

print("****************************数 据 类 型 转 换****************************")
print()#自动换行

a1  =   0.22222
b1  =  int(a1)                      # 数据转换,强制转换
print(b1)


Guess you like

Origin blog.csdn.net/Naiva/article/details/104760456