Python Quick Start (1) Introduction to common containers and built-in functions

Bibliography: Dong Fuguo "Python Data Analysis, Mining and Visualization" 

Table of contents

1. Definitions of lists, tuples, dictionaries and sets

Two, the string

3. Operators

3.1 Arithmetic operators

3.2 Membership Operators

3.3 Membership Test Operators

3.4 Set operators

3.5 Logical operators

4. Commonly used built-in functions

4.1 Type conversion

4.1.1 int(), float(), complex()

4.1.2 Conversion of binary numbers

4.1.3 Encoding and Character Conversion

4.1.4 Common container conversion

4.1.5 eval function (commonly used)

4.2 Maximum value, minimum value 

4.3 Number of elements, summation

4.4 Sorting, reverse order

4.4.1 sorted()

4.4.2 reversed()

4.5 Input and output

4.6 range( )

4.7 zip( )

4.8 map(), reduce(), and filter() 

4.8.1 map()

4.8.2 reduce()

4.8.3 filter()

5. Comprehensive exercises

1. Output the sum of single digits

2. Flip the input string

3. Output the maximum value in the list entered by the user

4. Conversion of integers and strings

5. Output a list of elements equivalent to True

6. Sort by rules

Summary of other knowledge points

 print function

Binary and character encoding

reserved word 

variable

string type

type conversion


1. Definitions of lists, tuples, dictionaries and sets

#分别创建列表,元组,字典和集合
x_list = [1,2,3]
x_tuple = (1,2,3)
x_dict = {'a':97,'b':98,'c':99}
x_set={1,2,3}

#输出列表的第2个元素,下标从0开始
print(x_list[1])

#输出元组的第2个元素
print(x_tuple[1])

#输出字典中键为a的对应的值
print(x_dict['a'])

#输出列表的长度
print(len(x_list))

#输出元组中元素2首次出现的位置
print(x_tuple.index(2))

#输出字典中值为98的对应的键的内容
for key,value in x_dict.items():
    if value==98:
        print(key)

#输出集合中最大的元素
print(max(x_set))

2
2
97
3
1
b
3

Two, the string

Strings can be defined using single quotes, double quotes, and triple quotes, and triple quotes allow the string content to wrap.

Adding r before the string can directly output the original string without escaping, so if there is a slash in the string that has the meaning of an escape character, you can directly use r to output the original string.

#字符串可以使用单引号、双引号和三引号进行定义,使用三引号可以允许字符串内容换行
text='''Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Really counts.
'''

#输出字符串的长度
print(len(text))

#统计字符串中is的个数
print(text.count('is'))

#是否存在该单词
print('beautiful' in text)

#输出20个=
print('='*20)

#使用+连接两个字符串进行输出
print('Good' + 'Morning')

#在字符串前加一个r表示原始字符串,无需进行转义
print(r'C:\Desktop\text.txt')

204
6
False
====================
GoodMorning

C:\Desktop\ext.txt

3. Operators

3.1 Arithmetic operators

+: Add operation, concatenate strings

-: subtraction operation, the operation of finding the difference between sets

*: new lists, tuples, etc. can be generated, which can represent the repetition of sequences

/, // : division, // round down

%: remainder operation, format string

**: Exponentiation

#2.1 算术运算符

print("运算符+")
# 运算法+可以用来连接字符串,列表,元组等等
print('abc'+'def')
print([1,2]+[3,4])
print((1,2)+(3,))
print('\n')

print("运算符-")
# 运算符-可以用来计算集合的差集
print({1,2,3}-{3,4,5})
print({3,4,5}-{1,2,3})
print('\n')

print("运算符*")
#可用于列表、元组、字符串等类型对象与整数的乘法,表示序列元素的重复,生成新的列表,元组或字符串
print('important things should be emphasised by 3 times\n'*3)
#生成新的列表,包含3个0
print([0]*3)
#生成新的元组,包含5个0
print((0,)*5)
print('\n')

print("运算符/和//")
#用来计算除法,//是向下取整
print(17/4)
print(17//4)
print((-17)/4)
print((-17)//4)
print('\n')

print("运算符%")
#可以进行求余运算,也可以用来格式化字符串
print(365%7)
#把65,97,48格式化为字符
print('%c,%c,%c'%(65,97,48))
print('\n')

print('**运算符:幂运算')
print(2**4)
print(3**3**3)
print((3**3)**3)
print(9**0.5)
print((-1)**0.5)
print('\n')

operator +
abcdef
[1, 2, 3, 4]
(1, 2, 3)


Operators -
{1, 2}
{4, 5}


运算符*
important things should be emphasised by 3 times
important things should be emphasised by 3 times
important things should be emphasised by 3 times

[0, 0, 0]
(0, 0, 0, 0, 0)


operator / and //
4.25
4
-4.25
-5


operator %
1
A,a,0


**Operator: exponentiation
16
7625597484987
19683
3.0
(6.123233995736766e-17+1j)

3.2 Membership Operators

Used to compare the size of values ​​between two objects, applicable to lists, tuples or strings, etc.

#等价于判断: 3==3 and 3>2
print(3==3>2)

#aASCII码值>A,所以直接得出结论
print('abc'>'ABCD')

#列表第一个元素85>11
print([85,101]>[11,200,65])

#集合1不是集合2的子集
print({1,2,3,4}<={3,4,5})

#元组中前3个元素相同,第一个元组元素更多
print((1,2,3,4)>(1,2,3))

True
True
True
False
True

3.3 Membership Test Operators

The member test operator in is used to test whether an object contains another object, and is applicable to lists, resource groups, dictionaries, collections, strings, and container objects such as range objects, zip objects, and filter objects that contain multiple elements. 

print('成员测试运算符in')
print(60 in [70,60,50,80])

print('abc' in 'a1b2c3d4')

print([3] in [[3],[4],[5]])

print('3' in map(str,range(5)))

print(4 in range(5))
print(5 in range(5))

print(4 in list(range(5)))

Membership Test Operator in
True
False
True True
True
True
False
True

 

3.4 Set operators

Set intersection: &

union: |

Symmetric difference: ^

Difference:- 

print("集合运算符")
A={35,45,55,65,75}
B={65,75,85,95}
#交集运算
print(A|B)
#并集运算
print(A&B)
#差集
print(A-B)
print(B-A)
#对称差集
print(A^B)

{65, 35, 75, 45, 85, 55, 95}
{65, 75}
{35, 45, 55}
{85, 95}
{35, 45, 85, 55, 95}

3.5 Logical operators

and: true if both expressions are true, otherwise false

or: If one of the two expressions is true, it will be true, and if both of them are false, then it will be false

False: 0, 0.0, 0j, None, False, empty list, empty tuple, empty string, empty dictionary, empty collection, empty range object or other empty container object

True: everything else is true except false

print("逻辑运算符")
print(3 in range(5) and 'abc' in 'abcdefg')
print(3-3 or 5-2)
#空值等价于false
print(not 5)
#非空列表等价于true
print(not [])

True

3

False

True

 

 

4. Commonly used built-in functions

4.1 Type conversion

4.1.1 int(), float(), complex()

Mutual conversion of numeric types

#1. 数字类型转换
print(int(3.5))
print(int('119'))
print(int('1111',2))
print(int('1111',8))
print(int('1111',16))
print(int('   9\n'))
#把字符串转换为浮点数
print(float('3.1415926'))
#复数的转换
print(complex(3,4))
print("\n")
3
119
15
585
4369
9
3.1415926
(3+4j)

 

4.1.2 Conversion of binary numbers

bin(): Convert an integer to a binary number

oct(): Convert an integer to a decimal number

hex() : Convert an integer to a hexadecimal number

#2. 进制类型转换
print(bin(8888))  #把整数转换为二进制数
print(oct(8888))  #把整数转换为八进制数
print(hex(8888))  #把整数转换为十六进制数
print("\n")
0b10001010111000
0o21270
0x22b8

 

4.1.3 Encoding and Character Conversion

 ord(): Returns the Unicode encoding of a single character

chr(): returns the character corresponding to the Unicode encoding

str(): Convert any type of argument to a string

#3. 编码和字符转换
print(ord('a'))   #返回字符的ASCII编码
print(ord('马'))  #返回汉字字符的Unicode编码
print(chr(65))    #返回指定ASCII码对应的字符
print(chr(39532)) #返回指定Unicode编码对应的汉字
print(str([1,2,3,4,5]))  #把列表转换为字符串
print(str({1,2,3,4,5}))  #把集合转换为字符串
print("\n")
97
39532
A
[1, 2, 3, 4, 5]
{1, 2, 3, 4, 5}

4.1.4 Common container conversion

Create lists, tuples, sets, dictionaries 

Note: when converting to a collection, it will automatically deduplicate

print(list(),tuple(),dict(),set()) #建立空的列表、元组、字典和集合
s={3,2,1,4}
print(list(s),tuple(s)) #把集合转换为列表和元组
lst=[1,2,3,3,4,5]
print(set(lst),tuple(lst)) #把列表转换为集合和元组,集合会自动去除重复的元素
print(str(lst)) #把列表转换为字符串,会在每个等号后面自动加一个空格
print(list(str(lst))) #把字符串转换为列表
print(dict(name='Ma',sex='Female',age='21')) #建立字典
print("\n")
[] () {} set()
[1, 2, 3, 4] (1, 2, 3, 4)
{1, 2, 3, 4, 5} (1, 2, 3, 3, 4, 5)
[1, 2, 3, 3, 4, 5]
['[', '1', ',', ' ', '2', ',', ' ', '3', ',', ' ', '3', ',', ' ', '4', ',', ' ', '5', ']']
{'name': 'Ma', 'sex': 'Female', 'age': '21'}

 

4.1.5 eval function (commonly used)

It can be used to calculate the value of a string or byte string, and can also implement type conversion to get the actual type of data in the string. If the user enters a list, it will be converted to a string through the input function, but it can be restored to the list 

#5. eval():计算字符串或者字节串的值
print(eval('3+4j'))  #对字符串求值得到负数
print(eval('8**2')) #对字符串求值得到8**2=16
print(eval('[1,2,3,4,5,6]')) #对字符串求值得到列表
print(eval('{1,2,3,4}')) #对字符串求值得到集合
print("\n")
(3+4j)
64
[1, 2, 3, 4, 5, 6]
{1, 2, 3, 4}

lst is a list object 

lst=eval(input('请输入一个列表:'))

4.2 Maximum value, minimum value 

The max and min functions are used to find the maximum and minimum values ​​of all elements in the sequence, where the input parameters can be list list, element tuple, dictionary dict, set set or other iterable objects containing a limited number of elements .

Advanced usage: Use the key parameter to specify the sorting rules, and the key can be equal to callable objects such as functions and lamba expressions.

 max/min(args,key=***)

 

iterable object:

(60 messages) What is an iterable object in python? _Indus snow's blog-CSDN blog_What does iterable object mean?  In python, iterable objects include lists, tuples , dictionaries, and strings; we often use them in combination with for loops. So the iteration here has a certain meaning, that is, the elements that can be placed behind for i in. In fact, we can also think of this type of element as a container. The simplest understanding is a box that can store many types of data.

 Lamba expression:

Equivalent to a function, you can use it when you want to use a function but don’t want to define it (to be added later)

(60 messages) Learning lambda expressions in Python_imzoer's Blog-CSDN Blog

 

#最大值、最小值
data = [3,22,111]
print(data)
print(max(data))
print(min(data))
#输出转换为字符串后的最大值,为字符3
print(max(data,key=str))

data = ['3','44','111']
print(max(data))
#返回最大长度的字符串
print(max(data,key=len))

data=['abc','Abcd','ab']
print(max(data))
print(max(data,key=len))
#返回全部转换为小写后最大长度的字符串
print(max(data,key=str.lower))

data=[1,1,2,3,2,2,1,3,1]
#统计列表中数字出现次数频率最大的数字,count方法仅限列表使用
print(max(set(data),key=data.count))
#统计最大元素的位置,getitem方法仅限列表使用
print(max(range(len(data)),key=data.__getitem__))
print("\n")
[3, 22, 111]
111
3
3
44
111
abc
Abcd
Abcd
1
3

4.3 Number of elements, summation

len(): Calculate the sequence length

sum(): calculates the sum of all elements in the sequence

Note: When using sum in a dictionary, the keys of the dictionary are summed, not the values ​​​​corresponding to the keys 

# 元素数量,求和
data = [1,2,3,4]
print(len(data))
print(sum(data))
data = (1,2,3)
print(len(data))
print(sum(data))
data='I love you baby'
print(len(data))
data={97:'a',65:'b',48:'0'}
print(len(data))
#对字典的键求和
print(sum(data))
print("\n")
4
10
3
6
15
3
210

4.4 Sorting, reverse order

4.4.1 sorted()

The sort function sorts an iterable and returns a new list .

  • Supports the use of keys for rule sorting. Keys can be callable objects such as functions and lamba expressions 
  • You can also use the reverse parameter to specify whether to sort in ascending order (reverse=False) or descending order (reverse=True). If not specified, the default is ascending order

shuffle randomly shuffle the order 

#1. 排序
from random import shuffle
data = list(range(20))
shuffle(data)
print(data)
print(sorted(data))
print(sorted(data,key=str))
print(sorted(data,key=str,reverse=True))
print("\n")
[16, 19, 17, 14, 3, 5, 1, 7, 0, 12, 18, 11, 10, 6, 13, 9, 8, 2, 15, 4]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 1, 0]

 

4.4.2 reversed()

reversed() can reverse iterable objects (except generator objects and zip, map, enumerate, and reversed objects with lazy evaluation ) and return iterable reversed objects .

Note: The reversed object has the characteristics of lazy evaluation, and the elements in it can only be used once. It does not support the use of the built-in function len() to count the number of elements, nor does it support the use of the built-in function reversed() to flip again.

 

 Lazy evaluation: Lazy evaluation does not require you to prepare all the elements in the entire iteration process in advance. The iterator only calculates an element when it iterates to an element, and before or after that, the element may not exist or be destroyed

(60 messages) Optimization in Python: Detailed explanation of lazy evaluation_Charles.zhang's blog-CSDN blog_python lazy evaluation

 

#2. 逆序
data1= list(range(20))
shuffle(data1)
print(data1)
reversedD = reversed(data1)
print(reversedD)
print(list(reversedD))
#空,因为reversed对象只能使用一次
print(tuple(reversedD))
[8, 3, 16, 9, 7, 18, 5, 1, 17, 4, 12, 0, 2, 13, 15, 19, 10, 11, 14, 6]
<list_reverseiterator object at 0x000001D490C06E80>
[6, 14, 11, 10, 19, 15, 13, 2, 0, 12, 4, 17, 1, 5, 18, 7, 9, 16, 3, 8]
()

 

4.5 Input and output

input function:

No matter what the user enters, input() always returns a string , and functions such as int(), float(), and eval() need to be used to perform type conversion on the content entered by the user. 

num=int(input('请输入一个大于2的自然数:'))
if num%2==0:
    print('这是一个偶数')
else:
    print('这是一个奇数')
lst=eval(input('请输入一个包含若干大于2的自然数的列表:'))
print('列表中的所有元素之和为:'+sum(lst))

print function: 

print(1,2,3,4,5,sep=',') #以逗号进行分割
print(1,2,3,4,5,end=' ') #以空格结尾,不换行
print(6,8,7)

4.6 range( )

The range object can be converted into a list, tuple or collection  , and the elements can be directly traversed using the for loop, and subscripts and slices are supported.

range1 = range(4)
#数字5-7
range2= range(5,8)
#从数字3开始,每次+4,要小于20
range3=range(3,20,4)
#从数字20开始,每次-3,要大于0
range4=range(20,0,-3)
#打印range对象
print(range1,range2,range3,range4)
#打印对应下标的range值
print(range4[2])
#把range对象转换为列表
print(list(range1))
print(list(range2))
print(list(range3))
print(list(range4))
#使用for循环遍历range对象
for i in range(10):
    print(i,end=' ')
range(0, 4) range(5, 8) range(3, 20, 4) range(20, 0, -3)
14
[0, 1, 2, 3]
[5, 6, 7]
[3, 7, 11, 15, 19]
[20, 17, 14, 11, 8, 5, 2]
0 1 2 3 4 5 6 7 8 9 

4.7 zip( )

 zip combines the elements at corresponding positions in multiple iterable objects together, and returns an iterable zip object. The final number of combined elements depends on the shorter one in the parameter sequence.

You can convert the zip object into a list or tuple and view its contents, or you can use a for loop to traverse the elements one by one.

Note : Each element in the zip object can only be used once, and the subscript cannot be used to access the element at the specified position. Zip does not support slice operations, nor can it be used as a parameter of len() and reversed(). 

#zip函数
data = zip('1234',[1,2,3,4,5,6])
print(data)
print(list(data))
#使用过一次zip对象后,zip对象中不再包含任何元素,如果想再次使用,需要重新定义zip对象
print(list(data))

data = zip('1234',[1,2,3,4,5,6])
print(tuple(data))

data = zip('1234',[1,2,3,4,5,6])
for i in data:
    print(i)
<zip object at 0x000001FA13EB40C0>
[('1', 1), ('2', 2), ('3', 3), ('4', 4)]
[]
(('1', 1), ('2', 2), ('3', 3), ('4', 4))
('1', 1)
('2', 2)
('3', 3)
('4', 4)

 

4.8 map(), reduce(), and filter() 

4.8.1 map()

The parameter passed in the map function needs to be an iterable type.

It is an error if you want to pass in int type, because int is not iterable 

 Map function:

Type conversion can be implemented, it can be converted to a list, tuple or collection, and the elements can also be traversed using a for loop.

Elements in a map object can only be used once.

from operator import add
m=map(str,range(5))
m1=map(int,range(10))
print(m)
print(m1)
print(list(m),'\n',list(m1))
#空,只能使用一次
print(tuple(m1))
print(list(map(len,['abc','12345','58fdsa'])))
#把字符串转换为整形列表
print(list(map(int,'12345')))
#把整数列表转换为字符串列表
print(list(map(str,[1,2,3,4,5])))
#相加,遍历
for num in map(add,range(5),range(5,10)):
    print(num)
<map object at 0x00000247FA707FA0>
<map object at 0x00000247FA707F70>
['0', '1', '2', '3', '4'] 
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
()
[3, 5, 6]
[1, 2, 3, 4, 5]
['1', '2', '3', '4', '5']
5
7
9
11
13

 

4.8.2 reduce()

Need to import to use

from functools import reduce

reduce can perform superposition operations, such as accumulation and multiplication. 

from functools import reduce
from operator import add,mul,or_

seq=range(1,10)
#对seq中的元素进行累加操作
print(reduce(add,seq))
#对seq的元素进行累乘操作
print(reduce(mul,seq))
seq=[{1},{2},{3},{4}]
#对seq中的集合使用并集运算
print(reduce(or_,seq))
#拼接列表中的元素
lst=['1','2','3','4','5']
print(reduce(add,lst))
45
362880
{1, 2, 3, 4}
12345

 

4.8.3 filter()

Filter elements in a sequence using specified rules.

Each element can only be used once.

seq = ['abcd','1234','.?,/','']
print(list(filter(str.isdigit,seq)))
print(list(filter(str.isalpha,seq)))
print(list(filter(str.isalnum,seq)))
print(list(filter(None,seq)))
['1234']
['abcd']
['abcd', '1234']
['abcd', '1234', '.?,/']

 

5. Comprehensive exercises

1. Output the sum of single digits

  • use of map
num=input('请输入一个正整数:')
m=map(int,num)
print('该正整数各位数字之和为:',sum(m))
  • The use of reduce 
from functools import reduce
from operator import add
m=list(map(int,input()))
print(reduce(add,m))

 

2. Flip the input string

  • The join function splits the string
num=input('请输入一个字符串:')
r=list(reversed(num))
print("".join(r))
  • Use the reversed object
from functools import reduce
from operator import add
t=input('请输入一个字符串:')
print(reduce(add,reversed(t)))

 

3. Output the maximum value in the list entered by the user

The use of max function and eval function 

lst = eval(input())
print(max(lst))

4. Conversion of integers and strings

Input a list containing some integers, convert all integers in the list to strings, and then output a list containing these strings

lst = list(map(str,input()))
print(lst)

5. Output a list of elements equivalent to True

Input a list containing a number of arbitrary elements, and output a list of elements in the list that are equivalent to True. Such as input [1,2,0, None, False, 'a'], output ['1', '2', 'a']

lst = eval(input())
print(list(filter(None,lst)))

 

6. Sort by rules

Input a list containing several integers, output a new list, in the new list, the odd numbers come first and the even numbers follow, and the relative order between the odd numbers remains the same, and the relative order between the even numbers also does not change

lst = eval(input())
newL = sorted(lst,key=lambda num:num%2==0)
print(newL)

Summary of other knowledge points

 print function

 Create file and write content

a+: If the file exists, append the content to the file; if the file does not exist, create a new file and write the content 

fp=open('G:/text.txt','a+')
print("helloworld",file=fp)
fp.close()

Binary and character encoding

In the ASCII code, 8 bits (one byte) in the computer can represent 256 states, and the ASCII code can represent 0-127, that is, 128 characters, and the remaining 128 are not enough, so different character sets have been introduced, such as GB2312 , GBK, GB18030

Unicode: In order to unify different encoding rules in various countries

utf-8: 3 bytes for Chinese, 1 byte for English

Unicode: Both Chinese and English use 2 bytes

example:

The Unicode encoding of multiplication is 4e58, converted to decimal is 20056, and binary is 100111001011000

The chr() function is a library function in Python to get a character value from a given ASCII code  (integer value), it takes a number (should be ASCII code  ) and returns the character.

The ord() function is a library function in Python used to get a numeric value from a given character value, it takes a character and returns an integer i.e. it is used to convert a character to an integer i.e. it is used to get an ASCII given character value  . _

print(chr(0b100111001011000))
print(ord('乘'))

20056

reserved word 

# 保留字
import keyword
print(keyword.kwlist)

variable

name='winnie'
print('值',name)
print('标识',id(name))
print('类型',type(name))

Reasons for inaccurate addition of floating point numbers:

Computers are stored in binary, and in some cases, the addition of floating-point numbers may be inaccurate.

from decimal import Decimal

print(1.1+2.2)

print(Decimal('1.1')+Decimal('2.2'))

string type

The effect of triple quotes:

str = 'Jet lag'
str2='''
今天
天气
好晴朗
'''
print(str2)

type conversion

name='winnie'
age=21
# print('我叫'+name+'今年'+age+'岁')  #错误,因为name和age的类型不一样,不能一起输出
print('我叫'+name+'今年'+str(age)+'岁')

Guess you like

Origin blog.csdn.net/weixin_45662399/article/details/127176769