Python----based modules, lists, tuples, dictionaries

Source: Internet
Author: User
Tags shallow copy

1. Module

When writing the module, try not to have the same name as the module that comes with the system.

When the module is called, it is looked up in the current directory for the module, and then it looks like a python environment variable.

A. Module 1:sys

The code is as follows:

1 Import sys2 print (Sys.path)  

The purpose of this code is to print out the Python environment variables as follows:

D:\\python Training \\s14\\day2

D:\\python Training \\s14

D:\\python35\\python35.zip

D:\\python35\\dlls

D:\\python35\\lib

D:\\python35

d:\\python35\\lib\\site-packages The third-party library will be here .

print (SYS.ARGV) # prints the relative path of the current file, but the absolute path printed in Pycharm is as follows:

[' D:/python training/s14/day2/sys_mod.py ']

B. Module 2:os

The code is as follows:

1 import os2 cmd = Os.system ("dir") #执行命令, do not save result 3 Cmd_res = Os.popen ("dir"). Read () #执行命令, save results 4 print ("--->", cmd_res) 5 OS . mkdir ("New_dir") #创建目录

2. Data type:

Number: integer (int) float (floating point type), no matter how large the 3.0python is int is 3.0 No long integer this concept

Boolean value: True or False 1 or 0

String

An example of a string operation:

Name= "Zhaofan" Print (Name.capitalize ())   #将字符串首字母大写print (Name.count ("a"))     #查找字符串中a的个数print (Name.center ( "-") #显示结果如下:---------------------zhaofan----------------------Print (Name.endswith ("an"))  # Determines whether the end of the string is Anprint ("My name is Zhaofan". Find ("name")) #返回字符串的索引print (Name.isalnum ())  # If the string includes both literal and numeric, return Trueprint ("Zhaofan". Isalpha ()) #如果字符串中都为字母则返回trueprint ("123123". IsDigit ())  # Determines whether the string is digitally print ("ZZZZ". Islower ())   #判断字符串是否为小写name. Strip () remove the front and back spaces Name.lstrip () remove the left space Name.rstrip () Remove the right space Name.replace () Replace Name.rfind ("character") to find the subscript name.split () of the rightmost character in the string  , separated by a space by default

Python3 does not equal only with! = To cancel the <> in 2.0

3. List

List features: Lists are ordered, lists can have duplicate values

list[ number] to remove the corresponding value from the list

About List slices:

List[1:2] starting from the second position, including the location, but not the end, that is, the second value of the Fetch list List[1],list[1:3] can take out the 2nd and 3rd values

List[-1] Take out the last value of the list

List[-2] Check out the list of two values

List[:3] Take out the top two values of a list

Increase of List

list.append (" element name") appends an element to the last list

Inserting a list

List.insert (1, "element name") Inserts an element in the first 2nd position of the list

Modification of the list

name[2]= " The new element name changes the 3rd element of the list

Deletion of the list

Name.remove ("element name") deletes the corresponding element in the list

del Names[1] Delete the corresponding element in the list

Name.pop () Delete the last value in the list if you do not have an output subscript, or delete the corresponding element if you delete the number subscript

Find the location of an element in a list, which is the subscript

name.index (" element name")

name.clear () List of conditions

name.count (" element name") to find out the number of an element in the list

Name.reverse () Reverses the elements in the list

Name.sort () to sort the list elements

name.extend (names2) incorporating name2 into the name list

del name2 You can delete the name2 list

4. about shades of a list

First shallow copy

name.copy () It 's a shallow copy .

Here is an example of a shallow copy code:

1 names = ["Zhafan", "Dean", [1,2,3,4], "Dean", "Dan", "Jack", "Yes", "a", "a"] 2 Names2 = names.copy () 3 print (names) 4 print (NA MES2) 5 names2[1]= "Zhaofan" 6 print (names) 7 print (NAMES2) 8  9 names[2][0]=10010 print (names) one print (Names2)

The result of the above code is as follows:

D:\python35\python.exe D:/python Training/s14/day2/copy_qian.py

[' Zhafan ', ' Dean ', [1, 2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

[' Zhafan ', ' Dean ', [1, 2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

[' Zhafan ', ' Dean ', [1, 2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

[' Zhafan ', ' Zhaofan ', [1, 2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

[' Zhafan ', ' Dean ', [2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

[' Zhafan ', ' Zhaofan ', [2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

Summary: As can be seen from the above results, names.copy () copies a list of the same as the names list When you modify the contents of the list,

If the list is nested in a list, then if the modification is the first level of the list, then only the modified list will be changed, and if the contents of the nested list are modified, the contents of the two list will change

Such as:

Here is a deep copy

Deep copy requires module copy

Deep copy, it is completely open up another memory space, and modify one of the list of any value, the other list will not change:

The code example is as follows:

1 import copy2 names = ["Zhafan", "Dean", [1,2,3,4], "Dean", "Dan", "Jack", "Yes", "a", "a"]3 Names2 = copy.deepcopy (names) 4 Print (names) 5 print (names2) 6 names[2][1]=100007 print (names) 8 print (NAMES2)

The results of the operation are as follows:

D:\python35\python.exe D:/python Training/s14/day2/copy_deep.py

[' Zhafan ', ' Dean ', [1, 2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

[' Zhafan ', ' Dean ', [1, 2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

[' Zhafan ', ' Dean ', [1, 10000, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

[' Zhafan ', ' Dean ', [1, 2, 3, 4], ' Dean ', ' Dan ', ' Jack ', ' Yes ', ' a ', ' a ']

As you can see from the code, modify the contents of one list and the other does not change

Print each element in the list

For I in Names:

Print I

5. Tuple tuples

Tuples are immutable lists, that is, once a tuple is initialized it cannot be modified, so a tuple cannot use such modified methods as append (), insert (), and so on in a list.

The code examples for tuples are as follows:

1 tt_tuple = ("Zhaofan", "Dean", "Jack") 2 print (Tt_tuple.count ("Dean")) 3 print (Tt_tuple.index ("Jack")) 4 print (tt_tuple [-1])

The results of the operation are as follows:

D:\python35\python.exe D:/python Training/s14/day2/tuple_ex.py

1

2

Jack

7. For an example of writing a simple shopping cart with List lists:

Program Requirements:

A. after starting the program, let the user enter the payroll and then print the list of items

B. allow users to purchase items based on their product number

c. After the user selects the product, checks whether the balance is enough, enough on the direct debit, enough to prompt the user

d. can exit at any time, when exiting, print the goods and balances that have been purchased

 1 goods_list=[["Iphone", 5288],["Bike", 1200],["Coffee", 20],["Ipad", 1800]] 2 shopping_list=[] 3 user_salary = input (" Please enter your salary as: ") 4 if User_salary.isdigit () is true:5 user_salary = Int (user_salary) 6 while true:7 for Key,i Term in Enumerate (goods_list): 8 print (key,iterm[0],iterm[1]) 9 User_choice = input ("What do you want to buy (enter the serial number of the product, Q table If User_choice.isdigit () is True:11 user_choice=int (user_choice), if User_cho             Ice > Len (goods_list): Print ("\033[31;1m the product number you entered does not exist \033[0m") Continue15 If GOODS_LIST[USER_CHOICE][1] < user_salary and User_choice > 0:16 shopping_list.append (goods_list[ User_choice]) user_salary-= goods_list[user_choice][1]18 Print ("\033[31;1m%s\033[0m has been Add to cart, your money is still remaining \033[31;1m%s\033[0m "% (goods_list[user_choice][0],user_salary)) Continue20 Else : Print ("\033[31;1m you don't have enough money, you only have the%s RMB \033[0m "%user_salary" if user_choice = = "Q": Print ("Your cart"). Center (50             , "-")) (Key,iterm in Enumerate (shopping_list): + print (key,iterm[0],iterm[1]) 27 Print ("You also have the remaining \033[31;1m%s\033[0m RMB"%user_salary) break29 else:30 print ("Please enter the correct salary")

8, about the dictionary Dict

The dictionary has the following characteristics:

1) Key-value format, key is unique

2) Disorder of

3) Fast Query Speed

An example of a simple dcit dictionary:

1 info = {' name ': ' Dean ', 2         ' job ': ' IT ', 3         ' age ': 23,4         ' company ': ' XDHT ' 5         }6 print (info)

The results of the operation are as follows:

D:\python35\python.exe D:/python Training/s14/day2/dcit-2.py

{' Company ': ' xdht ', ' name ': ' Dean ', ' Age ': ' ' job ': ' IT '}

It can be seen from here that the dictionary is unordered.

The search and change of dictionaries and additions

There is also a delete data, but if the dictionary is empty, the error will be Info.pop ("name")

The code example is as follows:

1 info = {' name ': ' Dean ', 2         ' job ': ' IT ', 3         ' age ': 23,4         ' company ': ' XDHT ' 5         }6 print (info) 7 info.pop ("name" )

The results of the program run as follows:

D:\python35\python.exe D:/python Training/s14/day2/dcit-2.py

{' name ': ' Dean ', ' Company ': ' Xdht ', ' Age ': ' ' job ': ' IT '}

{' Company ': ' Xdht ', ' age ': +, ' job ': ' IT '}

Process finished with exit code 0

But if you use Info.pop (), the deleted data does not exist, it will be an error.

Converts the key,value of dict into a list display

Print (Info.items ())

The effect is as follows:

D:\python35\python.exe D:/python Training/s14/day2/dcit-2.py

Dict_items (' job ', ' IT '), (' Company ', ' Xdht '), (' Age ', ' + '), (' Name ', ' Dean ')])

In particular, the use of Has_key () was canceled in python3.0.

Instead, the method is either in or not

code example:

if "name" in info :

Print ("OK")

According to the list ABC to create the Dict key, the next test is the default value, if not specified is None

info = {}

info = Info.fromkeys (["A", "B", "C"], "test")

Print (info)

The results of the operation are as follows:

info = {}

info = Info.fromkeys (["A", "B", "C"], "test")

Print (info)

Info.keys () # print out the key of the dictionary

info.values () # print out the value of the dictionary

Method 1

For key in info:

Print (Key,info[key])

Method 2

For k,v in Info.items ():

Print (K,V)

In practice, try not to use Method 2, because the efficiency of Method 2 is lower than the efficiency of Method 1, Method 2 will first convert the Dict dictionary to list, so when the data is large do not use

9, about the dictionary nesting, the code example is as follows:

1 menu_dict={2     "Henan province": {3         "Jiaozuo": {4             "Xiuwu County": {"AA", "BB", "CC"}, 5             "Wuzhi County": {"DD", "EE", "FF"}, 6             "Boai County": {" GG "," HH "," II "} 7         }, 8         " Xinxiang ": {9             " Hui County ": {" AA "," BB "," CC "},10             " Fengqiu County ": {" DD "," EE "," FF "},11             " Yanjin County ": {" GG "," HH "," II "}12         }13     },14     " Hebei province ": {" Xingtai ": {             " Ningjin ": {" AA "," BB "," CC "},17             " Neiqiu County ": {" DD " , "EE", "FF"},18             "Xingtai County": {"GG", "HH", "II"}19         },20         "Tangshan": {             "leting": {"AA", "BB", "CC"},22             "Tanghai County" : {"DD", "EE", "FF"},23             "Yutian County": {"GG", "HH", "II"}24         }25     }26}

Python----based modules, lists, tuples, dictionaries

Related Article

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.