Python Learning Notes (lists, tuples, shopping cart instances)

Source: Internet
Author: User
Tags shallow copy

First, List

Lists and dictionaries are two of the most common data types

1. Requirements: How to store the class more than 80 people's name, how to achieve?

names = ["Zhangyang","Guyun","Xiangpeng","Xuliangchen"]Print(Names[0],names[2])#Remove Zhangyang XiangpengPrint(Names[2:4])#Slice, remove "Xiangpeng", "Xuliangchen" and outputPrint(Names[0:4])#slices, remove "Zhangyang", "Guyun", "Xiangpeng", "Xuliangchen"]Print(Names[-1])#slices, negative numbers refer from backward to forwardPrint(names[-2:])#take the last 2 values

Note: The front and back 0 can be omitted

2. Examples of various operations of the list

" Zhangyang Guyun Xiangpeng xuliangchen " # take this list as an example

Increase:

Names.append ("leihaidong"# added at the end of the list

Insert:

Names.insert (1,"chenronghua"# position 1, inserting Data Names.insert (3," Xinzhiyu " # position 3, inserting data

Modify:

" Xiedi " # Subscript position 2, replace with "Xiedi"

Delete: (Three ways)

Names.remove ("chenronghua"# deletes the specified data in the list del#  Delete the data of subscript position 1 # no subscript, delete the last data; add subscript, same as Del effect

Copy:

(1)

names = ["zhangyang","guyun","Xiangpeng ","xuliangchen"= names.copy () names[" Xiangpeng " Print (names) Print (Names2)

(2)

A.

names = ["Zhangyang","Guyun","Xiangpeng",["Alex","Jack"],"Xuliangchen"]names2= Names.copy ()#shallow copy, copy only the first layerNAMES[2] ="Xiangpeng"names[3][0] ="ALEX"Print(names)Print(Names2)

View the output, Names2, Xiangpeng is not changed, the data in the sub-list is modified. Because the data in the child list is just a memory address, copy only the memory address

B. Shallow copy, The purpose of shallow copy: Create a federated account

ImportCopynames= ["Zhangyang","Guyun","Xiangpeng",["Alex","Jack"],"Xuliangchen"]names2=copy.copy (names)Print(names)Print(names2) names[2] ="Xiangpeng"names[3][0] ="ALEX"Print(names)Print(Names2)

(3) deep copy

ImportCopynames= ["Zhangyang","Guyun","Xiangpeng",["Alex","Jack"],"Xuliangchen"]names2=copy.deepcopy (names)Print(names)Print(names2) names[2] ="Xiangpeng"names[3][0] ="ALEX"Print(names)Print(Names2)

At this point,names and Names2 will be two separate data.

List loop:

 for inch names:     Print (i)

List slices:

Print (Names[0:-1:2]) Print (Name[::2])

The above two commands have the same effect, and the data in the output list is spaced out. 0 and 1 in the list operation can be omitted.

Two, the meta-group

Tuples are actually similar to the list, but also to save a group of numbers, but once it is created, it can no longer be modified, so it is called a read-only list.

Grammar:

Names = ('Alex','jack')

Tuples have only 2 methods, one is count, the other is index

Third, the procedure practice

Program: Shopping Cart Program

Demand:

    1. After you start the program, let the user enter the payroll, and then print the list of items
    2. Allow users to purchase items based on their product number
    3. After the user selects the product, checks whether the balance is enough, enough on the direct debit, enough to remind
    4. You can exit at any time to print the purchased goods and balances when exiting

The code is as follows:

Shopping_list = []#List of purchased items, pre-defined empty listSalary = input ("Please input your saraly:")#Let the user enter the payroll after starting the programProduct_list = [    ('iphone', 5800),    ('Bike', 800),    ('Coffee', 31),    ('Macbook Pro', 12000),    ('Alex Python', 81),    ('a', 120)]ifSalary.isdigit (): Salary=Int (Salary) whileTrue: forIndex,iteminchEnumerate (product_list):#take data and subscript from a list of items            #Print (Product_list.index (item), item)            Print(index,item) User_choice= Input ("Choose the item you want to buy? >>>:")        ifUser_choice.isdigit ():#If you enter a numberuser_choice = Int (user_choice)#go to data type            ifUser_choice < Len (product_list) andUser_choice >= 0:#Enter The shopping process if the product serial number entered is within the list subscript rangeP_item =Product_list[user_choice]ifP_item[1] <= Salary:#can affordShopping_list.append (p_item) Salary-= P_item[1]                    Print("Added%s to shopping cart,your current balance is \033[31;1m%s\033[0m"%(p_item,salary))Else:                    Print("\033[41;1m your balance remains [%s], you can't afford to buy this item \033[0m"%salary)Else:                Print("product code [%s] is not exist!!!"%User_choice)elifUser_choice = ='Q':            Print("---------Shopping list---------")             forPinchshopping_list:Print(P)Print("Your Current Balance:", Salary) exit ()Else:            Print("Invalid option")

Python Learning Notes (lists, tuples, shopping cart instances)

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.