search

python basics one

Dec 16, 2016 pm 04:25 PM
python basics

About memory allocation issues

Newly defined string variables open up a new memory space by default

Other similar indexes such as lists, tuples or dictionaries are actually just pointing the variable name to the same address space, as shown below

1 ##The new definition of string opens up a new memory space 2 >>> str1 = 'hoho' 3 >>> str2 = str1 4 >>> id(str1), id(str2) #View the memory object address, observe the memory address, that is, str2 has newly opened up memory space 5 (140297199501752, 140297199501752) #The same thing you see here is caused by an internal mechanism of Python, if the string is large enough It will be different, don't worry 6 >>> str2 = 'heihei' 7 >>> str1 8 'hoho' 9 >>> str210 'heihei'11 >>> ; id (str1), id (str2) (can be understood as a label) points to the same memory address, taking a dictionary as an example, as shown below15 >>> dic1 = {'name':'hoho'}16 >>> dic2 = dic117 >> ;> id(dic1),id(dic2)18 (140297199190088, 140297199190088)19 >>> dic1 = {'name':'hoho'}20 >>> dic2 = dic121 >> > id(dic1),id(dic2) #Check the memory object address and find that it is the same, so modify dic2. In fact, dic1 is also modified 22 (140297199191752, 140297199191752)23 >>> dic2['name' ] = 'heihei'24 >>> dic225 {'name': 'heihei'}26 >>> dic127 {'name': 'heihei'}

List, tuple and dictionary Copy problem (use of shallow copy and deep copy copy module)

1. Lists and tuples can use slices to implement shallow copy, or you can use the copy module to use shallow copy (including dictionary)

2. Use copy.deepcopy( ) Example deep copy

1 >>> import copy 2 >>> list1 = [1,2] 3 >>> list2 = list1 4 >>> list2[0] = 2 #list2 has changed, list1 has changed accordingly 5 >>> list1 6 [2, 2] 7 >>> list3 = list1[:] #Shallow complexity, use array slicing to do shallow copy 8 > ;>> list3 = copy.copy(list1) 9 >>> id(list1),id(list2),id(list3) #Here you can see that the address spaces are different 10 (140297199250696, 140297199250696, 140297199247560)11 >>>
12 >>> list4 = [1,[2]] ##Complex structures must use deep copy 13 >>> list5 = list4[:]14 >>> list515 [1, [2]]16 >>> list5[1][0] = 617 >>> list418 [1, [6]] #You can see it from here In fact, the inner list is not copied, and list4 has also changed accordingly19 >>> list6 = copy.deepcopy(list4) #Deep copy is used here20 >>> list6[1][0] = 821 >>> list622 [1, [8]]23 >>> list424 [1, [6]] #Here you can see what has been copied

Commonly used built-in functions

There are a lot of built-in functions in Python. Just remember the commonly used ones, but you will know how to check which built-in functions there are. The help of the function

Normally, it is divided into three steps

type (variable) ---> Get the variable The class it belongs to

dir (class name) ---> Check what methods are available under the class. Among them, those starting with double underscores like __abs__ generally have alternative methods, such as: __abs__ abs()

help (class name or function name) ---> View the function usage under the class or directly view the function usage

Shaping


1 >>> s,y = divmod(7,3) ## divmod returns data, the value is (quotient, remainder), which can be used for paging 2 >>> s,y3 (2, 1)4 >>> a = -25 >>> abs (-2) #abs takes the absolute value 6 27 >>> len(str(-2)) #takes the speed length 8 2

View Code

Floating point


1 >> > a = 7.02 >>> divmod(a,3)3 (2.0, 1.0)4 >>> a = 7.2355 >>> a.__round__(2) #Round to 6 7.247 > ;>> a.__trunc__() #Round to 8 7

View Code

String


1 >>> str1 = 'this is a string' 2 >>> 'is' in str1 #Member judgment 3 True 4 >>> str1[1:3] # Slicing operation and Index 5 'hi' 6 >>> len(str1) #Length 7 16 8 >>> str1.find('is') ; str1.find('is',3,9)11 512 >>> str1.find('iss') #If not found, return -1. If it is index, an error 13 will be reported -114 >>> str1.index('is',3)15 516 >>> str1.index('iss')17 Traceback (most recent call last):18 File "", line 1, in 19 ValueError: substring not found20 >>> str1 = ' aaa'21 >>> str1.strip() Remove blanks, line feeds, and enter 22 'aaa'23 >>> str1.lstrip()24 'aaa' 25 >>> str1.rstrip()26 ' aaa'27 >>> str1 = 'duiqi'  #Alignment operation 28 >>> str1.ljust(20)29 'duiqi ;>> str1.ljust(20,'*')31 'duiqi******************'32 >>> str1.rjust(20,'*' )33 '******************duiqi'34 >>> str1.center(20,'*')35 '************duiqi*** *****'36 >>> str1 = 'this is a string'37 >>> str1.split()            ##Split operation 38 ['this', 'is', 'a' , 'string'] 39 > ->'.join([str(i) for i in list1]) #Connection operation 43 '1->2->3'44 >>> str145 'this is a string'46 > >> str1.count('is') #Count 47 248 >>> str1.replace('is','os') #Replace 49 'thos os a string'50 >>> str1.replace('is','os',1) #Replace, only replace one 51 'thos is a string'52 53 str1.startswith('sub') #What starts with 54 str1.endswith('sub' ) #What ends with 55 str1.lower() #Convert to lowercase 56 str1.upper() #Convert to uppercase

View Code

List and tuple (tuple cannot be modified)


1 > >> lst1 = ['a'] 2 >>> lst1.append('b') #Add 3 >>> lst1 4 ['a', 'b'] 5 > >> lst2 = ['c','d'] 6 >>> lst1.extend(lst2) #Extend new 7 >>> lst1 8 ['a', 'b', 'c', 'd'] 9 >>> lst1.insert(0,'z') #insert10 >>> lst111 ['z', 'a', 'b', 'c ', 'd']12 >>> lst1.pop() #Remove the end 13 'd'14 >>> lst115 ['z', 'a', 'b', 'c'] 16 >>> lst1.remove('z') #Delete the specified element 17 >>> lst118 ['a', 'b', 'c']19 >>> lst1 = [ 'a', 'b', 'c', 'd']20 >>> lst2 = lst1.copy() # Only shallow copy python3 has 21 >>> lst2 = lst1.copy() 22 >>> lst223 ['a', 'b', 'c', 'd']24 >>> lst2.clear() #Clear the list 25 >>> lst226 [] 27 >>> del lst2 #Delete list 28 >>> lst129 ['d', 'c', 'b', 'a']30 >>> lst1.sort() # Sort 31 >>> lst132 ['a', 'b', 'c', 'd']33 >>> lst1.append('a')34 >>> lst1. count('a') #Count 35 236 >>> lst137 ['a', 'b', 'c', 'd', 'a']38 >>> len(lst1) # Length 39 540 >>> lst1.index('a') #Index 41 042 >>> lst1.index('a',1) #Index 43 4

View Code

Dictionary


1 >>> dic1 = {'key1' : 'a','key2' : 'b'} 2 >>> dic1.get('key1') #Get the dictionary value, not found Returns None by default, you can also specify 3 'a' 4 >>> dic1.get('key3') 5 >>> dic1.items() 6 dict_items([('key2', 'b' ), ('key1', 'a')]) #Return tuple list 7 >>> list(dic1.items()) 8 [('key2', 'b'), ('key1', 'a')] 9 >>> dic1.keys() #Return keys list 10 dict_keys(['key2', 'key1'])11 >>> dic1.values()   #Return value list 12 dict_values(['b', 'a'])13 >>> dic2 = dic1.copy() #Shallow copy 14 >>> dic215 {'key2': 'b', 'key1' : 'a'}16 >>> dic1['key3'] = 'c' #Assignment (modification)17 >>> dic118 {'key2': 'b', 'key1': 'a ', 'key3': 'c'}19 >>> dic1.pop('key1') #Delete the specified key20 'a'21 >>> dic122 {'key2': 'b', 'key3': 'c'}23 >>> dic1.get('key1','a') #Value, no 'a'24 'a'25 >>> dic126 {' key2': 'b', 'key3': 'c'}27 >>> dic1.setdefault('key1','a') #Set the default (seems useless) 28 'a'29 >> ;> dic130 {'key2': 'b', 'key1': 'a', 'key3': 'c'}31 >>> dic3 = {'name':'update'}32 > >> dic1.update(dic3) #Update 33 >>> dic1 34 {'key2': 'b', 'name': 'update', 'key1': 'a', 'key3': 'c'}35 >>> del dic3 #Delete 36 >>> dic137 {'key2': 'b', 'name': 'update', 'key1': 'a', 'key3 ': 'c'}38 >>> len(dic1) #Length 39 4

View Code

The above is the content of python basic one. For more related articles, please pay attention to the PHP Chinese website (www.php. cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor