Python Basics-02

Source: Internet
Author: User

Common types of data

List

In Python, the creation of a list can be made up of [] two square brackets. In other languages, it is called an array.

The list can hold a set of values, and the system defaults to each meta-index value in the list for easy lookup and use.

As follows:

#创建一个列表, and save certain data user_list = [' Andy Lau ', ' Jacky ', ' Jane Zhang ', ' Aaron Kwok ', ' Li Bai ']print (user_list) #[' Andy Lau ', ' Jacky ', ' Jane Zhang ', ' Aaron Kwok ', ' Li Bai ']# Read data print (User_list[0]) based on index value #刘德华

In practical applications, we can easily retrieve the values we want by indexed values.

At this point, if you need to remove multiple consecutive values from the list, you can use the following notation:

1 #创建存储了多个值得列表2 3 start_list = [' Andy Lau ', ' Jacky ', ' Jane Zhang ', ' Aaron Kwok ', ' Li Bai ']4 5 #此时, need to remove Jacky to Aaron Kwok 6 s_list = start_list[1:4]7 8 Print (S_lis t)   # [' Jacky ', ' Jane Zhang ', ' Aaron Kwok ']

In the above code, at the time of the value, we used 1:4, the index value from Jacky Cheung's 1 to Li Bai's 4, but Li Bai was not selected, at this time the principle is Gu Tou disregard the tail
And such an operation, which we call slicing

Tip: After slicing , the original array is not changed.

Then, starting from the left, the index value starts at 0, and if you start from the right, the index value starts at 1.

If you need to take a right-to-left value, one thing to note, for example:

#创建存储了多个值得列表start_list = [' Andy Lau ', ' Jacky ', ' Jane Zhang ', ' Aaron Kwok ', ' Li Bai ']

To take a value from right to Zo Libai to Jane Zhang, the following is the notation:

N_list = Start_list[-3:]print (n_list)

From right to left, Li Bai is-1, then 1 is omitted, to take the value to Jane Zhang, then Jane Zhang Index is-3, then write [-3:].

Similarly, if you take a value from left to right, you can omit the front if it is 0.

Additional

If we need to append some elements to the list, we can use the Append method to append some elements to the end of the list.

#创建一个列表user_list = [' Song ', ' Zhao Si ', ' Liu Can ', ' little Shenyang '] #向列表中追加元素user_list. Append (' Zhao Benshan ') #检测原列表是否被改变print (user_list)

Results of the output:

[' Song ', ' Zhao Si ', ' Liu Can ', ' Little Shenyang ', ' Zhao Benshan ']

The newly appended content has been appended to the end of the list.

If you need to insert an element before an element, you can use the Insert method.
As follows:

User_list = [' Song ', ' Zhao Si ', ' Liu Can ', ' little Shenyang '] #将添加的内容添加到赵四的前面user_list. Insert (1, ' Zhao Benshan ') print (user_list)

The results are as follows:

[' Song ', ' Zhao Benshan ', ' Zhao Si ', ' Liu Can ', ' Little Shenyang ']

The new data has been added successfully.

Change

If you need to modify an item in the list, you can find the element directly from the index value and give the new value directly.

As follows:

User_list[0] = ' Errenzhuan '

Delete

If you need to remove elements from the list, you can use remove, Del, or pop.

Remove method:

#创建一个列表user_list = [' Test 1 ', ' Test 2 ', ' Test 3 ', ' Test 4 '] #使用remove方式删除元素user_list. Remove (' Test 1 ') print (user_list)

Del method:

#创建一个列表user_list = [' Test 1 ', ' Test 2 ', ' Test 3 ', ' Test 4 '] #使用del method to delete del user_list[1]print (user_list)

Pop method:

#创建一个列表user_list = [' Test 1 ', ' Test 2 ', ' Test 3 ', ' Test 4 '] #使用pop方法删除user_list. Pop () print (user_list)

Tip: The Pop method above does not pass parameters at this time, the last value in the list will be deleted by default, and of course, the Pop () method also accepts the incoming parameter [index value of the list], so once the pop has passed the index value, its functional effect is equivalent to the Del method.

Summarize

Increase

Using the Append method, insert method

Delete

Using the Remove, Del, and Pop methods

Change

Use index values directly to find elements and assign new values

Check

Data can be queried by indexed values

We can also use the index method to query the indexed value of an element in the list.

As follows:

#创建列表user_list = [' Test 1 ', ' Test 2 ', ' Test 3 ']index_user = User_list.index (' Test 2 ') print (index_user) # 1

In the list, if you want to see the number of occurrences of an element, you can use the Count method

As follows:

#创建列表user_list = [' Test 1 ', ' Test 2 ', ' Test 3 ', ' Test 2 ', ' Test 3 ']# use the Count method to count the number of occurrences of an element in the list num = User_list.count (' Test 2 ') print (num) # 2  indicates that test 2 appeared twice.

Clear List

Empty list in Python can use the Clear method

As follows:

#创建列表user_list = [' Test 1 ', ' Test 2 ', ' Test 3 ', ' Test 2 ', ' Test 3 '] #使用clear方法清空列表user_list. Clear (); #检查列表是否被清空print (User_list) #显示为 [] , the list has been successfully emptied.

Reverse List

Reverse list in Python using the reverse method

As follows:

#创建列表user_list = [' Test 1 ', ' Test 2 ', ' Test 3 ', ' Test 2 ', ' Test 3 '] #使用reverse方法反转列表user_list. Reverse () print (user_list)

Sort

Sort the list in Python using the Sort method

As follows:

#创建列表list = [' 2ceshi2 ', ' #Ceshi1 ', ' ACeshi3 ', ' ACeshi4 ']list.sort () print (list)

The results are as follows:

[' #Ceshi1 ', ' 2ceshi2 ', ' ACeshi3 ', ' aCeshi4 ']

Then the order of the sorting is actually sorted in ASCII code order.

Merge List

The list in Python can be merged, using the Extend method

As follows:

#创建列表list = [' 2ceshi2 ', ' #Ceshi1 ', ' ACeshi3 ', ' aCeshi4 '] #创建第二个列表test_list = [1,2,3,4] #将第二个列表合并到list列表中list. Extend ( test_list) print (list,test_list)

In the above code, Test_list is successfully merged into the list, and the original test_list lists still exist.

Delete entire list

As follows:

The name of the Del list

Copy

In Python, the Copy method can be used for replication of the list, while the copy method is divided into deep and shallow copy.

First look at shallow copy:

1 "2 copy     () method replication 3  4     Shallow copy 5  6 There     can also be lists in the list, and other data types can exist, while shallow copy refers to copying only the first layer, and the second layer list 7     The content in the copy only copies pointers to memory addresses 8 ' ' 9 10 # Create a list of test_list = [' Alex ', ' Libai ', ' zhangxueyou ', ' zhaosi ']12 test2 = test_list.copy () 14 Print (test2) #[' Alex ', ' Libai ', ' zhangxueyou ', ' Zhaosi ']16 17 # change an element value in the first level list [test_list[0] = ' Hello,world ' 19 20 # Check Check for Change success print (test_list) # success #检查test2是否更改第一个元素24 print (TEST2) # The second list has not changed

At this point in the preceding code, the list test_list the first value, and the first value copied by the Test2 list is unchanged.

If there is still a list in the list test_list, in the case of shallow replication, the following situation occurs:

# Create a list-and the list has a list of level two test_list = [' Alex ', ' Libai ', ' zhangxueyou ', ' Zhaosi ', [' Nihao ', ' yanyan ']]test2 = Test_list.copy () # The first list has all been copied # change the value of a subset list in the first list test_list[4][0] = [' Nihao ']# see if test2 list changes print (TEST2)

Discover that the Test2 list has changed at this time:

[' Alex ', ' Libai ', ' zhangxueyou ', ' Zhaosi ', [[' Nihao '], ' Yanyan ']

The reason is that the copy is shallow copy, only to the first layer, the second layer of the list is not copied, just copied a pointer to the direction of memory.

Deep replication requires the introduction of a copy module

The code is as follows:

Import copy# Create List list_user = [' Alex ', ' Libai ', ' Zhaobenshan ', [' Yanyan ', ' yuping ']]# for deep replication new_list = Copy.deepcopy (list_ User) #print (new_list) # Copy succeeded # Change first set of list list_user[3][0] = "Yanyan" Print (list_user) print (new_list)

Deep replication is achieved by introducing the copy module and using the Deepcopy method

Loop List

The list of loops uses the for: In Can.

The code is as follows:

# Create List test_list = [' Alex ', ' Libai ', ' Shaopengtao ', ' Wangmengchan ']for i in Test_list:    print (i) # Loop succeeded

Supplemental: Code slices

When we print the list, we can use slices, for example

Test_list = [' Alex ', ' Libai ', ' Shaopengtao ', ' Wangmengchan ']

Have such a list, and now want to slice the position of the list 0 to-1,

Print (0:-1)

So at this point if you want to make a slice based on each of the two select one, the code can be written as follows:

Print (0:-1:2)

The effect of the final implementation is as follows:

[' Alex ', ' Shaopengtao ']

So in the process of slicing, if the start or end of the position is 0 or 1 can be omitted, so the above code becomes the following:

Print (:: 2)

The results are also unchanged.

Knowledge point additions and summaries:

Above, we say that the use of shallow replication, in fact, in the context of practical applications, there are probably three ways to achieve shallow replication, such as the following demonstration code, will demonstrate three types of shallow replication:

1     Import copy 2     # Create List 3     test_list = [' name ', [' deposit ', ' +] ' 4  5     ' 6 ' three     notation for shallow replication: 7  8     Copy Method 9     [:]10 list11 ', ' "'" '     The first way, using copy.copy14     new_list = copy.copy (test_list)     Print (new_list) "     #第二种方式19     new_list = test_list[:]20     print (new_list) 21     ""     #第三种方式24     new_list = List (test_list)     print (new_list)

Application of Shallow replication

For example, a husband and wife have a common bank account, in which there is a common property, one of whom takes money or saves, and the balance shown in the other is definitely to be changed.

The code is as follows:

# Create a list to show couples sharing a bank account needs money = [' name ', [' Deposit ', 2000]]# create two different people libai = Money[:]yanyan = money[:] #此时当丈夫libai Took 1000 libai[0] = ' Libai ' libai[1][1] = 2000-1000yanyan[0] = ' Yanyan ' # at this time, either the husband Libai or the wife Yanyan the bank balance will become less, Because two people share an account print (Libai) print (Yanyan)

The simple point is to realize the shared account through shallow copy, of course, the above application is just a simple example, in practice, the bank will not store the data in the list.

Tuple (tuple)

Tuples are actually similar to lists, that is, a set of numbers, but once created, it cannot be modified again, so it is called a read-only list.

The tuple itself can only be sliced and queried but cannot be changed.

The code is as follows:

Names = (' Alex ', ' Libai ', ' Jack ')

In the tuple object, there are only two methods, one is count and the other is index.

Small Exercise: Shopping cart

Demand:

The code is as follows:

 1 #!/usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author:li Bai 4 5 # Create List 6 product_list = [7 (' Iphone ', 5800), 8 (' Mac Pro ', 9800), 9 (' Bike ', Max.), (' Watch ', 10600), one (' Coffee ', 31), 12]13 14 # Create an empty list to store items purchased by users 15 Shopping_list = []16] salary = input (' Input your Salary: ') 18 # Determine if the user input is a digital if Salary.isdigit (): 20 # Converts the user input to int integer Type salary = Int (salary) 22 # Loop Output list all while true:24 # output the contents and index values in the product list for the Index,item in Enume         Rate (Product_list): 26 # Output print (index,item) User_choice = input (' Hello, please enter the purchased product serial number: ') 29 # Determine if user input is an ordinal number if User_choice.isdigit (): user_choice = Int (user_choice) 32 # Award Whether the product serial number entered by the user is reasonable, if User_choice < Len (product_list) and User_choice >= 0:34 print (user _choice) P_item = product_list[user_choice]36 # Determine if the user's property is adequate if p_item[ 1] <= Salary: # buy 38                     Shopping_list.append (p_item) # Save user-selected items into Shopp_list list salary-=p_item[1] # reduce property List of items to be purchased 40 # Print the balance of the property printing ("Add%s into shopping cart, your current balance is%s                 "% (p_item,salary)) else:43 print (' Your balance is left only%s, the balance is not sufficient '% salary) else:45 Print ("Product code [%s] is not exist!" % user_choice) elif User_choice = = ' Q ': print ("--------shopping list------") for P I         n shopping_list:49 print (p) print ("Your Current balance:", salary) Wuyi exit () 52 else:53 Print ("Invalid option")

Python Basics-02

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.