Lists are the most commonly used Python data type , It can appear as a comma separated value in square brackets .
The data items of a list do not need to have the same type
Create a list , Just enclose the different data items separated by commas in square brackets
Code understanding : Index of the list , Addition, deletion and modification of list data , And the use of list derivation
# list
all_in_list=[0.3,'hello','True']
print(' The list data is :',end='')
print(all_in_list)
# The forward index starts from
res=all_in_list[0]
print('all_in_list[0] The value of is :',end='')
print(res)
# Reverse all slave -1 Start
res=all_in_list[-2]
print('all_in_list[-2] The value of is :',end='')
print(res)
# Slice of the list , Left closed right away
res=all_in_list[0:2]
print('all_in_list[0:2] The slice value of is :',end='')
print(res)
# The new element in the end
all_in_list.append('hello world')
# Insert the element before the specified position , Become an element in the specified position
all_in_list.insert(0,'pre-hello')
print(' Add the new element as :',end='')
print(all_in_list)
# Remove elements
all_in_list.remove('hello world')
# Delete the first two elements
del all_in_list[:2]
print(' After deleting the element, it is :',end='')
print(all_in_list)
# Modify element values
all_in_list[0]=100
print(' Modify the element to :',end='')
print(all_in_list)
# for loop
x=[]
for i in range(10):
x.append(i)
print('for After adding the element in a loop, it is :',end='')
print(x)
# List derivation
b=[i for i in range(1,11)]
c=[i**2 for i in range(1,11)]
d=[i**2 for i in range(1,11) if i%2==0]
print(' The value of each list derivation is :',end='')
print(b)
print(c)
print(d)
# practice 1: Find the area of curved trapezoid
import math
n=10000
width=2*math.pi/n
# Method 1 : utilize for Loop through the core data structure
x=[]
y=[]
for i in range(n):
x.append(i*width)
for i in x:
y.append(abs(math.sin(i)))
S=sum(y)*width
print(' Method the area of a curved trapezoid is :',end='')
print(S)
# Method 2 : Use list derivation to build the core data structure
s=[abs(math.sin(i*width))*width for i in range(n)]
print(' Methods the area of the trapezoid with two curved edges is :',end='')
print(sum(s))
Code run results
Python Languages often use the following types of operators : Arithmetic operator 、 Compare relational operators 、 Assignment operator 、 Logical operators
Code understanding : Logical controller 、 Inclusion of strings in、 Conditional statements 、 Exchange value operation of bubble sort
# Python Logical controller
res=1<2
print('1<2 The correctness of the :',end='')
print(res)
res=1<2<3
print('1<2<3 The correctness of the :',end='')
print(res)
res='Name'=='name'
print("'Name'=='name' The correctness of the :",end='')
print(res)
res='M' in 'magic'
print("'M' stay 'magic' Correctness in :",end='')
print(res)
# Conditional decision statement
if 1<2:
print(' If 1<2 correct , The output :', end='')
print('1.hello')
if 1<0:
print(' If 1<0 correct , The output :', end='')
print('2.hello')
else:
print(' If 1<0 Incorrect , The output :', end='')
print('2.world')
if 1<0:
print(' If 1<0 correct , The output :', end='')
print('3.hello')
elif 2<1:
print(' If 1<0 Incorrect , but 2<1 correct , The output :', end='')
print('3.world')
else:
print(' If 1<0 Incorrect , And 2<1 It's not true either , The output :', end='')
print('3.hehe')
# Bubble sort
x=[1,2,6,0.3,2,0.5,-1,2.4]
print(' The value before bubble sorting is :', end='')
print(x)
n=len(x)
for i in range(n):
for j in range(i):
if x[j]>x[i]:
# Exchange value
x[i],x[j]=x[j],x[i]
print(' The value after bubble sorting is :', end='')
print(x)
Code run results
Dictionary is another variable container model , And can store any type of object .
Each key value of the dictionary key:value Yes, with a colon : Division , Comma between each key value pair , Division , The whole dictionary is enclosed in curly brackets {} in , The format is as follows :d = {key1 : value1, key2 : value2 }
Code understanding : According to the dictionary index value , Modified value , add value , Delete value , And dictionary derivation to generate dictionary
# Dictionaries
dic={'h':'hello',0.5:[0.2,0.3],'w':'world'}
print(' The dictionary data is :',end='')
print(dic)
# According to the key index value
res=dic['h']
print("dic['h'] The corresponding value is :",end='')
print(res)
# Modify an element according to the key
dic['h']=100
print(" The revised dictionary is :",end='')
print(dic)
# Add an element
dic['hw']='hello world'
print(" The dictionary after adding a key value is :",end='')
print(dic)
# Add multiple elements at the same time
dic.update({1:2,3:4})
print(" The dictionary after adding multiple key values is :",end='')
print(dic)
# Delete an element according to the key
del dic['h']
print(" The dictionary after deleting the key value is :",end='')
print(dic)
# Dictionary derivation
a={i:i**2 for i in range(10)}
print(" The dictionary generated by dictionary derivation is :",end='')
print(a)
Code run results
The string is Python The most commonly used data type in . We can use quotation marks ( ' or " ) To create a string .
Creating a string is simple , Just assign a value to the variable .
Code understanding : There are two ways to generate strings with and without line breaks 、 Index of a string , Basic operation of splicing 、 String segmentation 、 All strings are lowercase
# character string , There is no difference between a double quoted string and a single quoted string
string="My name"
print(' The generated string is :'+string)
# Three quotation marks can be used for line breaking
string='''My
name
'''
print(' The generated string with newline is :'+string)
string='My name'
print(' Single quotation marks and double quotation marks generate the same string , It's for :'+string)
print(string)
# The first element of the index string
print(' The first element of the string is :'+string[0])
# The first two elements of the index string
print(' The first two elements of the string are :'+string[:2])
# Repeat the string twice
print(' Repeat the string twice as :'+string*2)
# String concatenation
print(' The splicing string is :',end='')
print(string+' is xxx')
# Split string , Divide by commas , The return result is a list
res=string.split(sep=',')
print(' The string is divided according to the comma and then is :',end='')
print(1,string)
# Change all string letters to lowercase
res=string.lower()
print(' Change all string letters to lowercase :',end='')
print(res)
Code run results
Code understanding
# File operations
f=open("Walden.txt","r")
# Read file contents
txt=f.read()
print(txt)
# Before reading the contents of the file 100 That's ok
txt=f.read(100)
print(txt)
f.close()
# Read the file line by line , And return to the list
f=open("Walden.txt","r")
txt_lines=f.readlines()
print(txt_lines)
f.close()
# practice 3: Read the words in the novel
import re
f=open("Walden.txt","r")
# The data type read in is string
txt=f.read()
f.close()
# Change the characters in the string to lowercase
txt=txt.lower()
# Remove the punctuation marks from the novel
txt=re.sub('[,.?:“\’!-]','',txt)
# Word segmentation
words=txt.split()
word_sq={}
for i in words:
if i not in word_sq.keys():
word_sq[i]=1
else:
word_sq[i]+=1
# Sort
res=sorted(word_sq.items(),key=lambda x:x[1],reverse=True)
print(res)
You can define a function that you want to function , Here are the simple rules :
Code understanding
# Function customization
# The first way
def Sum(x,y):
return x+y
# The second way , Simple customization of functions
# return x The square of
y=lambda x:x**2
# return x The first element of
y1=lambda x:x[1]
res=Sum(1,2)
print(res)
res=y(10)
print(res)
res=y1(['hello',0])
print(res)
# practice 4: User defined function for finding the even number of sequences
def su(x):
z=0
for i in x:
if i%2==0:
z+=1
return z
res=su([1,2,3,4,5,6])
print(res)
Some basic features of object orientation :
Code understanding
# The difference between method and function
all_in_list=[2.5,'hello','world',3]
string='My name'
all_in_list.append('hehe')
# For string objects , It's not append Methodical
#string.append('Y’)
res=string.split()
# split It's a method , Is a method only available for string objects
#all_in_list.split()
print(all_in_list)
print(res)
# object-oriented
class Human:
def __init__(self,ag=None,se=None):
# Attributes of a class
self.age=ag
self.sex=se
# Class method
def square(self,x):
return x**2
zhangfei=Human(ag=23,se=' male ')
res=zhangfei.square(10)
print(res)
res=zhangfei.age
print(res)
res=zhangfei.sex
print(res)
Python Basic knowledge of One . First knowledge of basic data types type : int( integer ) stay 32 On the bit machine , The number of digits of an integer is 32 position , The value range is -2**31-2**31-1, namely -2147483648-2147483647 stay 64 position ...
The following content , As python Supplement of basic knowledge , It mainly involves the creation and characteristics of basic data types , And new data types Bytes Introduction of type
python Basic knowledge of ( One ) One .python Introduction to development Python Was founded by Guido van Rossum.1989 During Christmas , In Amsterdam ,Guido In order to kill the boredom of Christmas , Determined to develop a new script ...
python Basic knowledge explanation ——@classmethod and @staticmethod The role of In a member function of a class , You can add @classmethod and @staticmethod Modifier , There is a certain difference between the two , Simple ...
This time python A hundred steps Encyclopedia of reptiles , There is a detailed analysis of the steps of the crawler , There are detailed comments on each step of the code , It can be grasped through this case python The characteristics of reptiles : 1. Crawler dispatch entry (crawler_main.py) # coding: ...
Abstract : Come into contact with by chance python voice , I think the grammar is simple . Powerful , Just a friend shared an online class <python Crawlers and data visualization >, So in work and leisure time to learn , And do the following course notes , The whole is roughly divided into 4 individual ...
Contact python It's been a while , The following for python The use of basic knowledge to do a complete comb :1) avoid ‘\n’ And so on : a) Using escape character ‘\’ b) Using the original characters ‘r’ print r'c:\now' ...
# -*- coding: utf-8 -*-# @Time : 2018-12-25 19:31# @Author : Three Jin aphrodisiac # @Email : [email protected]# @Fi ...
Python Basic knowledge of (Basic knowledge) 1. know Python& Basic environment construction 2.Python Basics ( On ) 3.Python Basics ( in ) 4.Python Basics ( Next ) 5.Python ...
1.Python brief introduction 1.1.Python Introduce python Founded by Guido · Van rosum (Guido van Rossum).1989 Christmas period of , Guido · Van rosum ( Chinese name : Uncle GUI ) To spend time in Amsterdam ...
1089 Longest text substring V2(Manacher Algorithm ) Base time limit :1 second Space restriction :131072 KB The score is : 0 difficulty : Basic questions Collection Focus on Palindrome string refers to aba.abba.cccbccc.aaaa ...
link: http://blog.okbase.net/haobao/archive/62.html by: I'm so full We need to be in XML And entity classes ,DataTable,List Switch between , Here is XmlU ...
Problem Description Although cao'er is a road maniac ( I have been in Hangdian for more than a year , Even people who get lost on campus , Khan, ~), But cao'er still likes traveling very much , Because on the journey I'll meet a lot of people ( Prince charming ,^0^), A lot of things , It's also abundant ...
This topic contains information about Windows Presentation Foundation (WPF) edition 4.5 Information about new and enhanced features in . This topic contains the following sections : Ribbon controls improve performance , Set the grouping when the display is large ...
spring-data-mongodb A system xml Two data sources are configured in the file The reference documents are as follows : http://www.iteye.com/problems/92789 http://stackoverfl ...
One . About the cause Recently Office Of QQ The group asked how to extract values from a string and add them up . If you use regular expressions, you can solve this problem very quickly . So today I'm going to talk about VB6/VBA Method and code for using regular expressions in , another ...
time & datetime modular import timeimport datetime# ## # print("ss")# #time.sleep(5)# # prin ...
summary The Demo Designed to deploy a simple spring boot engineering , Including data editing and viewing functions POM To configure <?xml version="1.0" encoding="UTF- ...
Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1 ...
Original source :www.cnblogs.com/Charltsing/p/CellLight.html QQ:564955427 Excel The implementation principle of cell row and column indication ( It is commonly known as spotlight function ) Cell row and column indication function is in recording ...