Learning python data types, one article is more than enough, a must-read for novices

Compression software and antivirus software are recommended


7 - zip

use tinder

1. Basic data types and variables (on)

2.1 Notes

advantage:

  1. code description

uncommented code

commented code

  1. The sentence that does not let the interpreter execute the comment

2.2 Single-line comments

Single-line comment shortcut key: ctrl + ?

2.3 Multi-line comments

"""""" (three double quotes)

2.4 Literal variables

字面量是已经被定义好的量
在程序中可以直接使用的字面量:1,2,3,4,5,6

185730213551

What is a variable: a quantity that can change

The box used by the computer to store data, if you want to use this data, just use the box directly

变量名 =

a = 10
print(a)

10

Don't equate the equal sign of an assignment statement with the equal sign of mathematics:

x = 10
x = x +2
a = 'abc'
b = a
a = 'edg'
print(b)

abc

illustrate:

1.变量就是可以变化的量,可以随时进行修改
2.程序是使用来处理数据的,而变量就是用来存贮数据的
3.变量就是一个存贮数据时,当前数据所在的内存地址的名字

multiple variable assignment

a, b, c = 1, 2, 'd'
print(a)
print(b)
print(c)

1
2
d

a = b = c = 1
print(a)
print(b)
print(c)

1
1
1

2.5 Identifiers and keywords

The rules are as follows:

  • Composed of numbers, letters, underscores
  • cannot start with a number
  • cannot use built-in keywords
  • Strictly case sensitive

2.6 Naming Convention

  • The name of the identifier should be clear from the name

name ,age ,

Follow the naming convention

  • CamelCase: Large CamelCase and Small CamelCase
  • Big hump: the first letter of each word is capitalized

First Name, Last Name

  • CamelCase: first word begins with a small letter; second word capitalizes the first letter

myName , youName

2.7 Keywords

Identifiers with special functions are keywords

Keywords cannot be declared as variable names

#打印python的所有关键字
import keyword
print(keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

2.8 Initialization of basic data types

value type

2.8.1 The integer type int

1 ,2 ,3, 100, 200, -300, 0

n = 78
print(n)

78

a = 1000_0000_0000_0000
b = 1000000000000000
print(a)
print(b)

1000000000000000
1000000000000000

2.8.2 Floating point type float

1.23×10^9

12.3×10^8

1.23 , 3.14, -9.1

1.23e9, 12.3e8, 0.000012==》1.2e-5

around

Two ways to represent floating point numbers

  • In decimal form, 1.2, 1.23, 12.3
  • Exponential form (scientific notation)
aen 或者 aEn
a为尾数部分,n是指数部分,E或e是固定的字符,用于分割尾数部分和指数部分
2.1e5 = 2.1×10^5 其中2.1是尾数,5是指数
3.7E-2 = 3.7×10^-2 其中3.7是尾数,-2是指数
0.5E7 = 0.5×10^7 其中0.5是尾数, 7是指数
14E3 = 14×10^3  其中14是尾数,3是指数

print(14E3)

float1 = 0.0000000000000000000847
print(float1)

14000.0
8.47e-20

2.8.3 Boolean value bool

There are only two values, True and False, pay attention to capitalization

True means true (indicating that the condition is met or established) ==》1

False means false (indicating that the condition is not satisfied or not established) == "0

print(3>2)
print(2>3)

True
False

2.8.4 String str

is not a numeric type, it is a sequence type

Any text enclosed in single quotes, double quotes, triple quotes, abc, xyz

basic use

name = 'python'
age = 18
jiaxiang = '湖北'
print(name+jiaxiang)  # 相加就是简单的字符串拼接
print(name*5) # 相乘就相当于将字符串和自己相加了5次

python湖北
pythonpythonpythonpythonpython

Two order of values:

  • The index from left to right starts from 0 by default, and the maximum range is 1 less than the length of the string
  • The index starts from right to left by default -1, and the maximum range is the beginning of the string
str3 = 'abcdefg'
print(str3[2])
print(str3[6])
print(str3[-1])

c
g
g

子字符串[初始位置:结束位置],包头不包尾 ,左闭右开
str3 = 'abcdefg'
print(str3[1:6])
print(str3[:6])
print(str3[3:])

bcdef
abcdef
defg

2.9 View data type

  • Variables don't have types, data have types

type (the name of the variable) == "view data type

a = 'ab'
b = 123
c = 1.23

print(type(a))
print(type(b))
print(type(c))

<class 'str'>
<class 'int'>
<class 'float'>

2.9.1 Escape character \

\n == "new line

\t == "Tab character, a tab key, that is, four spaces

\ \ ==》\

Escape characters must be written in quotation marks, escaping is making him stupid

print('床前明月光,\n疑是地上霜')
print('床前明月光,\t疑是地上霜')

床前明月光,
疑是地上霜
床前明月光,	疑是地上霜

print('\\\n\\')

\
\
height = 175.0
print('您的身高是:'+height) # 报错
print('您的身高是:'+str(height))

i = int('123')
print(i)
ii = ('123个')
print(ii)


您的身高是:175.0
123
123

See here to leave an easter egg for everyone, beginner homework

1.用变量给自己建立个角色信息,要输出出来
    姓名
    年龄
    身高
    家乡
    兴趣
    是否有编程基础
2.有一个字符串变量  s = '人生苦短,我学python'
    通过下标索引,分别输出 苦,学 o 这几个字符


2. Data type (below)

1.1 List Generation

list [1,2,3,4,5,6,7,8,9]

list1 = [1,2,3,4,5,6,7,8,9]
print(list1)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

print(list(range(1,10)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

1.1.1 Ordinary list comprehensions

# 普通写法
li = []
for i in range(1,10):
    li.append(i)
print(li)

# 列表生成式写法
print([i for i in range(1,10)])
[1*1,2*2,3*3,4*4,...,9*9]
# 普通写法
li = []
for i in range(1,10):
    li.append(i*i)
print(li)

# 列表生成式
print([i*i for i in range(1,10)])
[1*2,2*3,3*4,...,9*10]
# 普通写法
li = []
for i in range(1,10):
    li.append(i*(i+1))
print(li)

# 列表生成式
print([i*(i+1) for i in range(1,10)])

[2, 6, 12, 20, 30, 42, 56, 72, 90]
[2, 6, 12, 20, 30, 42, 56, 72, 90]
# 求偶数 ,普通写法
li = []
for i in range(1,11):
    if i % 2 == 0:
        li.append(i)
print(li)

# 带if的列表生成式
print([i for i in range(1,11) if i % 2 == 0])

[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]

Use two layers of loops to generate all possible combinations (ABC and 123)

# 普通写法
li = []
for i in 'ABC':
    for j in '123':
        li.append(i+j)
print(li)

# 双层循环写法
print([i+j for i in 'ABC' for j in  '123'])

['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']

1.2 tuple tuple

Tuples usually use a pair of parentheses to surround all elements, but parentheses are not required

tuple1 = 'python教程', 'Java'
print(tuple1)
print(type(tuple1))

1.2.1 Check

count()
tuple2 = (123, 'Google', 'JD', 'Taobao', 123)
print(tuple2.count(123))  # 2
print(tuple2.count('JD'))

2
1
index()
检索某个元素的下标值
t = (123, 'Google', 'JD', 'Taobao', 123)
print(t.index(123))
print(t.index(123,1))

0
4

1.2.2 Function

1相加,两个元组相加生成一个新的元组
data = ('张三', '李四') + ('王五', '赵六')
print(data)
('张三', '李四', '王五', '赵六')

2.相乘
data = ('张三', '李四')*2
print(data)
('张三', '李四', '张三', '李四')

3.获取长度
data = ('张三', '李四')
print(len(data))
2
4.索引
data = ('张三', '李四', '王五', '赵六')
print(data[0])
print(data[1])
print(data[2])
print(data[3])

张三
李四
王五
赵六

5.切片
data = ('张三', '李四', '王五', '赵六')
print(data[0:3])
('张三', '李四', '王五')

6.步长,隔多少取值
data = ('张三', '李四', '王五', '赵六')
print(data[1:4:2]) # 1是开始位置,4是结束位置,2是步长
('李四', '赵六')

7.for循环
data = ('张三', '李四', '王五', '赵六')
for i in data:
    if i == '李四':
        continue  # 结束本次循环 ,继续执行下一次循环
    print(i)
    
张三
王五
赵六

The tuple itself is immutable. If the tuple contains other mutable elements, these mutable elements can be changed

1.3 String formatted output

你好某某某 我叫某某某 再见某某某
name = 'python'
age = 18
print('大家好, 我叫'+name+', 我今年'+str(age)+'岁')

1.3.1% method (placeholder)

%s = 字符串 ==》只能放在字符串里面
%d = 整数 ==》 只能放整数
%f = 小数 ==》默认保留六位小数
	%.1f ==> 保留一位小数
    %.2f ==> 保留两位小数
语法:('xx%dxxx%s'%(变量1,变量2)# 或者带入变量数据
name = 'python'
age = 18
height = 175.0
print('你好,我叫%s, 今年%d岁了, 身高%f'%(name,age,height))
print('你好,我叫%s, 今年%d岁了, 身高%.1f'%(name,age,height))
print('你好,我叫%s, 今年%d岁了, 身高%.2f'%(name,age,height))

你好,我叫python, 今年18岁了, 身高175.000000
你好,我叫python, 今年18岁了, 身高175.0
你好,我叫python, 今年18岁了, 身高175.00

s = '我叫%s, 今年%d岁了, 身高%f'
print(s%('python', 15, 175.0))

我叫python, 今年15岁了, 身高175.000000

1.3.2 format()

语法:
name = 'python'
age = 18
height = 175.0
print('你好, 我叫{},今年{}岁了,身高{}'.format(name,age,height))

传入的数据类型是不限的,字符串,元组,列表都行
数据跟{
    
    }顺序从左到右一一对应
直接传数据
传入多个数据:
'{}{}{}'.format(数据1,数据2,数据3print('你好,我叫{},今年{}岁了,身高{}'.format('python',18,175.0))
自定义数据:
'{下标}{下标}'.format(数据1,数据2)
print('你好,我叫{0},今年{2}岁了,身高{1}'.format('python',175.0,18))

1.3.3 f-format

语法:在字符串里面加上一个f/F,把要输出的变量用大括号{
    
    }包裹
name = 'python'
age = 18
height = 175.0
print(f'大家好,我叫{
      
      name},我今年{
      
      age}岁了,身高是{
      
      height}')
print(f'大家好,我叫{
      
      name[0]},我今年{
      
      age+1}岁了,身高是{
      
      height-10}')

大家好,我叫python,我今年18岁了,身高是175.0
大家好,我叫p,我今年19岁了,身高是165.0




Advanced Three Data Types (Part 1)

2.1 Hash type

1. Data type: int, float, bool ==> store a value

2. Sequence type: str, list, tuple == "store multiple data

3. Hash type

Unordered inner elements do not repeat and do not have subscripts

2.1.1 Dictionary dict

It is used to save some data types with typical corresponding relationships, and is characterized by using key-value pairs to store data

key === > key value===> value

Syntax for key-value pairs: key:value

Manifestations:

{}, but if the key-value pairs are stored in the curly braces, then it is a dictionary

lookup value by key

dictionary name[key]

The key of the dictionary cannot be repeated, if it is repeated, the value of the last repeated key will be taken

call = {
    
    'python':'11234', 'look':'11235', '阿尔法':'11236'}
user = {
    
    '姓名':'python', '年龄':18, '工作':'python讲师'}

print(call['python'])
print(user['工作'])

dict1 = {
    
    'a':1, 'b':2, 'a':3, 'a':4}
print(dict1)

11234
python讲师
{
    
    'a': 4, 'b': 2}

variability

dict1 = {
    
    'a':1, 'b':2, 'a':3, 'a':4}
dict1['b'] = 100
print(dict1)
{
    
    'a': 4, 'b': 100}

When we want to represent a set of fixed information, using a dictionary can be more intuitive

字典包含多个键值对,key是字典的关键数据,程序对字典的操作都是基于key的
- 通过key访问value
- 通过key添加key-value对
- 通过key删除key-value对
- 通过key修改key-value对
- 通过key判断指定key-value对是否存在
通过key访问value
scores = {
    
    '语文':89}
print(scores['语文'])

如果腰围字典添加key-value对,就只需要为不存的key赋值就可以了
scores['数学'] = 93
scores[92] = 8.4
print(scores)

如果要删除字典中的键值对,就可以使用del语句
del scores['语文']
del scores['数学']
print(scores)

对存在的键值对赋值,新的值会覆盖原来的值
cars = {
    
    'bmw':88, 'benchi':83, 'tesila':95}
cars['benchi'] = 4.3
cars['tesila'] = 3.8
print(cars)

判断字典是否包含指定的key,使用in或者not in
in  not in # in 包含   not in 不包含
cars = {
    
    'bmw':88, 'benchi':83, 'tesila':95}
print('tesila' in cars)
print('baoshijie' in cars)
print('BYD' not in cars)

The key of the dictionary can be any immutable type

The dictionary allows direct assignment to non-existent keys, so that a key-value pair can be added

common method

字典方法
print(dir(dict))

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 
 
 
 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

2.1.1.1 clear()

Used to clear all key-value pairs in the point

cars = {
    
    'bmw':88, 'benchi':83, 'tesila':95}
print(cars)
cars.clear()
print(cars)

{
    
    'bmw': 88, 'benchi': 83, 'tesila': 95}
{
    
    }

2.1.1.2 get()

Get the value according to the key

cars = {
    
    'bmw':88, 'benchi':83, 'tesila':95}
print(cars.get('bmw'))
print(cars.get('baoshijie'))
print(cars['baoshijie'])

88
None
    print(cars['baoshijie']) # 报错
KeyError: 'baoshijie'

where to roll over (tuple)

data = (99,88,77,['left hand',18],33,22,11)

data[3] [0] = ‘look’

print(data)

Elements are immutable but can be changed if there is a variable type inside the element, but only limited to the variable elements inside the tuple

eggs

# 1.将列表数据[1,2,3,2,1,4,4,4,2,5,6,7,7,9,8,10,10]去重

# 2.有字典 dic = {"k1":"v1","k2":"v2","k3":"v3"},实现以下功能:
(1)、遍历字典 dic 中所有的key
(2)、遍历字典 dic 中所有的value
(3)、循环遍历字典 dic中所有的key和value
(4)、添加一个键值对"k4","v4",输出添加后的字典 dic
(5)、删除字典 dic 中的键值对"k1" "v1",并输出删除后的字典 dic
(6) 获取字典 dic中“k2"对应的值
# 3.students =[
{'name':'go','age':18,'score':98,'tel':'18888888888', gender':'female'},
{'name''Java'age :20 'score':95."tel’: 18888888889' 'aender'.'unkown'},
{'name':'python' 'age' 18 'score':88.'tel':'18888888810' 'gender':'male'},
{'name':'php','age':16,'score':58,'tel':'18888888811', 'gender':'unkown'},
{'name':'c' 'age':19.'score':78.'tel':'18888888812' 'gender': male'},
{'name':'c++' 'age':17.'score':92,'tel':'18888888813','gender':'male'},
]

#(1)统计及格学生的个数
#(2)打印不及格学生的名字和对应的成绩
# #(3)删除性别不明的所有的学生



4. Advanced data types (middle)

1.1 update()

You can use the key-value pairs contained in a dictionary to update an existing dictionary. If the updated dictionary contains the corresponding key-value pairs, the original value will be overwritten. If not, it will be added.

cars = {
    
    'bmw':88, 'benchi':83,'tesila':95}
cars.update({
    
    'bmw':4.5,'baoshijie':9.3})
print(cars)
{
    
    'bmw': 4.5, 'benchi': 83, 'tesila': 95, 'baoshijie': 9.3}

1.2 items(), keys(), values()

dict_items, dict_keys, dict_values ​​objects, python does not want users to directly operate these methods, but they can be converted into lists through the list() function

items()==》取键值对
cars = {
    
    'bmw':88, 'benchi':83,'tesila':95}
ims = cars.items()
print(ims)
print(type(ims))
print(list(ims))
print(list(ims)[1])

dict_items([('bmw', 88), ('benchi', 83), ('tesila', 95)])
<class 'dict_items'>
[('bmw', 88), ('benchi', 83), ('tesila', 95)]
('benchi', 83)

keys()==> 取键
cars = {
    
    'bmw':88, 'benchi':83,'tesila':95}
kys = cars.keys()
print(kys)
print(type(kys))
print(list(kys))
print(list(kys)[1])

dict_keys(['bmw', 'benchi', 'tesila'])
<class 'dict_keys'>
['bmw', 'benchi', 'tesila']
benchi

cars = {
    
    'bmw':88, 'benchi':83,'tesila':95}
vals = cars.values()
print(vals)
print(type(vals))
print(list(vals))
print(list(vals)[1])

dict_values([88, 83, 95])
<class 'dict_values'>
[88, 83, 95]
83

After the program calls the three methods of the dictionary, they all need to be called to convert them into a list, so that the return values ​​of these three methods can be converted into a list

1.3 pop()

Used to get the value corresponding to the specified key and delete the key-value pair

cars = {
    
    'bmw':88, 'benchi':83,'tesila':95}
print(cars.pop('tesila'))
print(cars)

95
{
    
    'bmw': 88, 'benchi': 83}

1.4 setdefault()

It can return the value corresponding to the specified key. If the key-value pair does not exist, it will first set the default value for this key, and then return the value corresponding to this key.

cars = {
    
    'bmw':88, 'benchi':83,'tesila':95}
print(cars.setdefault('baoshijie',92))#两个参数,第二个是设置默认值,如果不存在就会新增键值对
print(cars)

92
{
    
    'bmw': 88, 'benchi': 83, 'tesila': 95, 'baoshijie': 92}

2.1 Dictionaries

2.1.1 Public functions

length

info = {
    
    'age':12, 'shengming':True, 'name':'fe'}
data = len(info)
print(data)

3

index (key)

info = {
    
    'age':12, 'shengming':True, 'name':'fe'}
print(info['name']) # fe  字典 通过键 查找值
print(info['age'])  #12
print(info['xxx'])  # 报错  如果键不存在会报错

fe
12
报错

value = info.get('xxx') # 使用get方法获取值如果不存在就打印None
print(value)
None

for loop

info = {
    
    'age':12, 'shengming':True, 'name':'fe'}
#直接遍历这个字典,可以获取所有的键
for item in info:
    print(item)  #所有键
    
age
shengming
name
#使用keys方法
for item in info.keys():
    print(item)  # 所有键
    
#使用values方法
for item in info.values():
    print(item)  # 所有值
    
#使用items方法
for key,value in info.items():
    print(key,value)  #  获取所有的键值

2.2 Collection

elements are unique and different from each other

{
    
    name1, name2, .....name n}
语法:
集合名 = {
    
    数据1,数据2,数据3,。。。。数据n}#如果有重复的数据,是不会被添加到内存空间里面

Data types such as lists, dictionaries, and collections cannot be stored, otherwise an error will be reported

#报错
print({
    
    {
    
    'a':1}})
print({
    
    [1,2,3]})
print({
    
    {
    
    1,2,3}})

It should be noted that the data in the collection must be guaranteed to be unique. The collection will only keep one copy of the data elements in the United States and China, that is, deduplication

s = {
    
    1,2,1,(1,2,3),'c','c'}
print(s)

{
    
    1, 2, (1, 2, 3), 'c'}

There is no order in set in python, and the order may be different each time it is output

set1 = {
    
    1,2,3,4,5,5,1,2,3,4,5,6,7,9,1}
print(set1)
# print(set1[1])
print(type(set1))

{
    
    1, 2, 3, 4, 5, 6, 7, 9}
<class 'set'>

Note : When creating an empty collection, you must use set() instead of {}, because {} is an empty dictionary by default

li1 = [] # 空列表
tu1 = () # 空元组
str1 = '' # 空字符串
dict1 = {
    
    } # 空字典
set1 = set() #空集合
# 去重并转为列表输出
li = [1,2,3,4,5,6,7,89,41,1,1,1]
# li1 = set(li)
# li2 = list(li1)
# print(li1)
# print(li2)

print(list(set(li)))
[1, 2, 3, 4, 5, 6, 7, 41, 89]

2.2.1 Mathematical operations on sets

operator operation python operator meaning
intersection & Get elements common to two collections
union | Get all the elements of the two sets
difference set - Get elements of one set that are not in another set
membership operation in 和 not in Determine whether an element is or is not in the collection
集合1 & 集合2——》判断交集
集合2 | 集合1——》判断并集
集合1 - 集合2——》判断差集

交集:两个集合里面共同有的数据
并集:两个集合里面的全部数据(不包括重复数据,集合本身也不能重复)
差集:集合1 - 集合2  减去共有的,剩下的就是差集


set1 = {
    
    1,2,3}
set2 = {
    
    3,4,5}
print(set1 & set2)
print(set1 | set2)
print(set1 - set2)# 差集{1, 2} 取一个集合中另一个集合没有的元素,将set1中属于set2的元素删除
print(set2 - set1)# 4,5
print(3 in set2)

{
    
    3}
{
    
    1, 2, 3, 4, 5}
{
    
    1, 2}
{
    
    4, 5}
True

The role of the collection:

  1. store unique data
  2. Used to deduplicate the sequence type and make logical judgments (intersection, union, difference)

2.2.2 Increase

The add() parameter is the object to be added. By adding data multiple times, it can be found that the position of the added element is uncertain

语法: 集合名.add(元素)
s = {
    
    'Java'}
s.add('python')
print(s)
s.add('go')
print(s)
s.add('c')
print(s)
s.add('c++')
print(s)

{
    
    'Java', 'python'}
{
    
    'go', 'Java', 'python'}
{
    
    'go', 'Java', 'python', 'c'}
{
    
    'c', 'c++', 'go', 'python', 'Java'}

The update() parameter is a sequence type, and each element will be iteratively added to the sequence (randomly added)

s = {
    
    'fe'}
s.update('123')
print(s)
s.update([4,5,6])
print(s)

{
    
    '3', '2', 'fe', '1'}
{
    
    '2', 4, 5, 6, '3', '1', 'fe'}

2.2.3 Delete

pop() removes an element at random

实际上在进行代码实验的时候并不是随机的
仅仅是在集合元素是字符串类型时,并且在cmd运行的时候才会随机删除,pycharm中默认保持删除第一个元素
s = {
    
    'fe'}
s.update('123')
print(s)
s.update([4,5,6])
print(s)
s.pop()
print(s)
s.pop()
print(s)

{
    
    '2', '1', 'fe', '3'}
{
    
    '1', 4, 'fe', 5, 6, '2', '3'}
{
    
    4, 'fe', 5, 6, '2', '3'}
{
    
    'fe', 5, 6, '2', '3'}

remove (parameter) has parameters, the parameter is the element to be deleted, if the element does not exist, an error will be reported

集合名.remove(元素)
s = {
    
    'fe'}
s.update('123')
print(s)
s.update([4,5,6])
print(s)
s.remove('1')
print(s)
s.remove('2')
print(s)
s.remove('8')
print(s)

{
    
    '1', 'fe', '2', '3'}
{
    
    4, 5, 6, '3', '1', '2', 'fe'}
{
    
    4, 5, 6, '3', '2', 'fe'}
{
    
    4, 5, 6, '3', 'fe'}
报错

discard() is similar to remove, but no error will be reported if the element does not exist

s = {
    
    'fe'}
s.update('123')
print(s)
s.update([4,5,6])
print(s)
s.discard('aaa')
print(s)

{
    
    '3', '1', 'fe', '2'}
{
    
    4, 5, 6, '3', 'fe', '1', '2'}
{
    
    4, 5, 6, '3', 'fe', '1', '2'}

clear() clears the elements in the collection

s = {
    
    'fe'}
s.update('123')
print(s)
s.update([4,5,6])
print(s)
s.clear()
print(s)

{
    
    '1', '3', '2', 'fe'}
{
    
    '2', 4, 5, 6, 'fe', '3', '1'}
set()

del () collection name (), delete the collection

# 整个吧盒子(变量)删除了,所以会报错,先删除了盒子,再去打印这个s就会报错显示盒子s不存在
s = {
    
    'fe'}
s.update('123')
print(s)
s.update([4,5,6])
print(s)
del s
print(s)

2.2.4 Change

由于set中的数据没有索引,也没有办法去定位一个元素,所以没办法直接修改
先删除在添加
s = {
    
    'A', 'B', 'C', 'D'}
# 把A改为E
s.remove('A')
s.add('E')
print(s)

{
    
    'B', 'E', 'C', 'D'}

2.2.5 check

set是一个可迭代对象,可以通过for循环进行遍历查询
s = {
    
    'A', 'B', 'C', 'D'}
for i in s:
    print(i)
    
A
C
D
B
复习巩固 练习题
 在终端中获取颜色(RGBA),打印描述信息,否则提示颜色不存在
    "R" -->"红色"
    "G" -->"绿色"
    "B" -->"蓝色"
    "A" -->"透明度"
# 1.将列表数据[1,2,3,2,1,4,4,4,2,5,6,7,7,9,8,10,10]去重
li1 = [1,2,3,2,1,4,4,4,2,5,6,7,7,9,8,10,10]
li2 = []
for i in li1:
    if i not in li2:
        li2.append(i)
print(li2)
#或者
print(list(set(li1)))

# 2.有字典 dic = {"k1": "v1", "k2": "v2", "k3": "v3"},实现以下功能:
# (1)、遍历字典 dic 中所有的key
dic = {
    
    "k1": "v1", "k2": "v2", "k3": "v3"}
for key in dic.keys():
    print(key)
# (2)、遍历字典 dic 中所有的value
for value in dic.values():
    print(value)
 # (3)、循环遍历字典 dic 中所有的key和value
for key,value in dic.items():
    print(key,value)
# (4)、添加一个键值对"k4","v4",输出添加后的字典 dic
dic['k4'] = 'v4'
print(dic)
# (5)、删除字典 dic 中的键值对"k1","v1",并输出删除后的字典 dic
dic.pop('k1')
print(dic)
# (6)、获取字典dic中“k2”对应的值
print(dic.get('k2'))

students = [
    {
    
    'name': 'Java', 'age': 18, 'score': 98, 'tel': '18888888888', 'gender': 'female'},
    {
    
    'name': 'c', 'age': 20, 'score': 95, 'tel': '18888888889', 'gender': 'unkown'},
    {
    
    'name': 'python', 'age': 18, 'score': 88, 'tel': '18888888810', 'gender': 'male'},
    {
    
    'name': 'c++', 'age': 16, 'score': 58, 'tel': '18888888811', 'gender': 'unkown'},
    {
    
    'name': 'php', 'age': 19, 'score': 78, 'tel': '18888888812', 'gender': 'male'},
    {
    
    'name': 'go', 'age': 17, 'score': 92, 'tel': '18888888813', 'gender': 'male'},
]
# (1)统计及格学生的个数
count = 0 #初始化一个值
for d in students:
    if d['score'] >= 60:
        count += 1
print(count)

# (2)打印不及格学生的名字和对应的成绩
for d in students:  #d是字典
    if d['score'] < 60:
        print(d['name'],d['score'])
# (3)删除性别不明的所有的学生
for d in students:
    if d['gender'] == 'unkown':
        #pop根据下标  remove根据值删除  clear 清空  del 列表名[下标]
        students.remove(d)  # 删除性别不明
print(students)





Review to consolidate answers

1.编写一个程序,检查任意一个年份是否是闰年
- 如果一个年份可以被4整除不能被100整除,或者可以被400整除,这个年份就是闰年
year = int(input('请输入一个年份:'))
if year % 4 == 0 and year % 100 != 0 or year %400 == 0:  # != 不相等
    print(year,'是闰年')
else:
    print(year,'是平年')

2.从键盘输入小明的期末成绩:
	当成绩为100时,'奖励一辆BMW'
    当成绩为(80-99)时,'奖励一台iphone'
    当成绩为(60-79)时,'奖励一本参考书'
    其他时,奖励棍子一根

3.计算1+2+3+...+100(使用while循环)

num = 1
sum = 0  # 初始化一个累计的变量
while num < 101:
    sum += num
    num += 1  # num1 =num + 1
print('num=',sum)

4.打印99乘法表:
1*1=1
1*2=2	2*2=4
1*3=3	2*3=6	3*3=9
1*4=4	2*4=8	3*4=12	4*4=16
1*5=5	2*5=10	3*5=15	4*5=20	5*5=25
1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36
1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49
1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64
1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81

for i in range(1,10):
    for j in range(1,i+1):
        print(i,'*',j,'=',i*j,end='\t')
    print()



Advanced Five Data Types (Part 2)

Python data types can be divided into three categories: numeric types, sequence types, hash types

Value type: int, float, bool

2.1 Sequence type

元素1  元素2   元素3  元素4 元素。。。。 元素n
 0      1      2       3    4         n-1
-n

# 元素下面的是索引取值
s = 'CSDN博客论坛'
print(s[0],'=',s[-8])
print(s[-1],'=',s[7])

C = C=

2.2 string str

A string is an ordered set of characters used to store and represent basic text information

2.2.1 Common methods

What is the most essential behavior of manipulating data? == "Addition, deletion, modification and query

字符串.方法名

2.2.1.1 find

The function of find: find the substring in a range, return the index value, and return -1 if there is no

grammar:

str.find(str,beg=0,end=len(string))
  • str==> specifies the string to retrieve
  • beg == "start index, the default value is 0
  • end == "end index, the default is the length of the string

find is often used to detect whether a string contains a substring str

s = 'hello world'
print(s.find('o'))  #o 的索引值就是4
print(s.find('hello')) # 找到hello则返回首个字符的索引
print(s.find('worldd')) # 找不到返回-1

s = ('python,helloworld,java,php')
print(s.find('h'))  # 返回的是首个h的下标
print(s.find('h',4))  # 从下标为4的地方开始找
print(s.rfind('h'))  # 从后往前找

2.2.1.2 index()

Check whether the substring str is contained in the string. If the range of beg and end is specified, check whether it is contained in the specified range, which is similar to find, except that if the substring is not in str, an error will be reported

s = ('python,helloworld,java,php')
print(s.index('world'))  # 12 索引值
print(s.index('worldd'))  # 报错

2.2.1.3 count()

Returns the number of substrings found

s = ('python,helloworld,java,php')
print(s.count('h'))  # 3 h的个数

2.2.1.4 strip()

Remove the spaces, newlines, and tabs on both sides of the string to get a new string

code = input('请输入4位的验证码:')
data = code.strip()
if data == 'ABCD':
    print('验证码正确')
else:
    print('验证码错误')

2.2.1.5 startswith(), endswith()

  • Determine whether the string starts with xx and get a Boolean value
dizhi = input('请输入住址:')
if dizhi.startswith('北京市'):
    print('北京人口')
else:
    print('非北京人口')
  • Determine whether the string has ended with xx and get a Boolean value
dizhi = input('请输入住址:')
if dizhi.endswith('村'):
    print('农业户口')
else:
    print('非农业户口')
s = '北京市朝阳区'
print(s.startswith('北京市'))

2.2.1.6 also

  • Determine whether the string is composed of numbers, and the returned result is a Boolean value
v1 = input('请输入第一个值:')
v2 = input('请输入第二个值:')
if v1.isdigit() and v2.isdigit():
    data = int(v1)+int(v2)
    print(data)
else:
    print('请输入正确的数字')

2.2.1.7lower() and upper()

The string is uppercased/lowercased to get a new string

lower() == "turn to lowercase

upper() == "turn to uppercase

s = 'C'
print(s)
s1 = s.lower()
print(s1)
s2 = s1.upper()
print(s2)

C
c
C

2.2.1.8 split()

Split the string, convert the string type into a list, the default is to split with spaces, and you can also specify characters to split

s = 'my name is zuoshou'
print(s.split())
s1 = 'python,helloworld,java,php'
print(s1.split(','))

['my', 'name', 'is', 'zuoshou']
['python', 'helloworld', 'java', 'php']

2.2.1.9 replace()

Replace the content of the string to get a new string

s = input('请输入评论信息:')
s1 = s.replace('草','*')
print(s1)

2.2.1.10 join()

Used to concatenate the elements in the sequence with the specified string to generate a new string

Often used to convert a list to a string

a = ['Java', '和', 'python', '是', '好朋友']
print(''.join(a))  # 常用于转化列表为字符串时使用
print('-'.join(a))

Java和python是好朋友
Java--python--好朋友

2.2.2 Common functions of strings

2.2.2.1 Forward fetching (from left to right), reverse fetching (from right to left, negative sign)

s = 'hello python'
# 正向取值
print(s[0])  #  取值为 h
print(s[5])  #  空格,空格也算是字符串里的一个字符
# 反向取值
print(s[-4]) # 取值为 t

len的用法
len 是从1开始数  计量字符串长度
print(s[len(s)-1])  # 最后一个值
print(len(s))   # len  计算字符串的长度
print(s[-len(s)])  # len 前面加负号 是从右到左取值

2.2.2.2 Slicing (regardless of head and tail, step size)

s = 'hello python'
print(s[::2])

hlopto

步长:0:9:2 第三个参数2代表步长,会从下标0开始,每次累加一个2就可以
print(s[0:9:2])

hlopt

print(s[::-1]) # 从右到左依次取值 反向取值 步长为负数就是从右到左 首尾不给值就是取所有
nohtyp olleh

2.3 list list

It can store multiple elements of different types and record multiple values ​​of the same attribute

List: store data of the same category for easy operation

字符串,不可变类型:创建好之后内部无法修改[内置功能都是新创建一份数据]
name = 'java'
data = name.upper()
print(name)
print(data)

java
JAVA  
列表,可变类型:创建好之后内部元素可以修改[独有功能基本上都是直接操作列表内部的,不会创建一份新的数据]

list1 = ['车子', '房子']
list1.append('妹子')  # append  ’添加‘的方法
print(list1)

['车子', '房子', '妹子']

list creation

列表名 = []

2.3.1 Increase

1.append:添加一个数据,添加到列表的最后一位
   语法: 列表名.append('python')
li..append('python')
print(li)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 'python']

2.insert: 添加一个数据到指定位置
    语法:列表名.insert(下标位置,内容)
   li.insert(0,'look')
print(li)
['look', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'python']

3.extend:添加一个序列类型到最后一位,并且吧序列类型拆分
    语法:列表名.extend(序列类型)
  li.extend('吸血鬼')
print(li)
li.extend(['吸血鬼'])
print(li)
['look', 2, 3, 4, 5, 6, 7, 8, 9, 10, '左手', '吸', '血', '鬼']
['look', 2, 3, 4, 5, 6, 7, 8, 9, 10, '左手', '吸', '血', '鬼', '吸血鬼']

2.3.2 Delete

pop:删除一个值,默认从最后一个开始删,也可以指定位置
    语法:列表名.pop()
    列表名.pop(下标)
    li.pop(-1)
print(li)
['look', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'python', '吸', '血', '鬼']

remove:删除一个指定的值,如果有多个,从第一个开始删
    语法:列表名.remove(删除对象)
    li.remove(3) # 删除对象
print(li)

['look', 2, 4, 5, 6, 7, 8, 9, 10, 'python', '吸', '血', '鬼']

clear :清空列表里面的所有数据
    语法:列表名.clear()
    li.clear()
print(li)

[]
del : 全局删除,可以删除一个变量
    语法:del 列表名[下标]
del li[3]  # 下标
print(li)

['look', 2, 4, 6, 7, 8, 9, 10, 'python', '吸', '血', '鬼']

2.3.3 Change

单个修改:直接通过下标进行修改
语法:列表名[下标] = 内容
li[1] = '阿尔法'
print(li)
['look', '阿尔法', 4, 6, 7, 8, 9, 10, 'python', '吸', '血', '鬼']

多个修改:通过切片的方式进行修改
语法: 列表名[起点:终点] = 数值1, 数值2
li[1:3] = 70,20
print(li)
['look', 70, 20, 6, 7, 8, 9, 10, '左手', '吸', '血', '鬼']

2.3.4 Check

index:根据内容获取指定数据的下标
    语法:列表名。index(要找的内容)
    print(li)
print(li.index(8)) 
5
列表名。index(要找的内容,起点值)
print(li.index(20,5)) #报错,显示20不在列表中

count:统计数据出现的次数
    语法:列表名.count(要找的内容)
    print(li.count(10))
          1

2.3.5 Others

排序(int的列表才可以排序)
sort:让列表的内容按照降序/升序的方式来排序
    列表名.sort()——》升序
li1 = [1,85,6,8,61,3,45321,1965]
li1.sort()
print(li1)

[1, 3, 6, 8, 61, 85, 1965, 45321]

    列表名.sort(reverse=True)——》降序
li1 = [1,85,6,8,61,3,45321,1965]
li1.sort(reverse=True)
print(li1)

[45321, 1965, 85, 61, 8, 6, 3, 1]

Guess you like

Origin blog.csdn.net/2201_75506216/article/details/131732582