Data types of Python learning

Source: Internet
Author: User
Tags shallow copy python list

1. Constants: All uppercase, unchanged variables

2..PYC file: Is the py file compiled after the binary file, the py file becomes the PYc file, the speed of loading increased, and PYC is a cross-platform bytecode, is executed by Python virtual machine. PYC content, is related to Python version, the different version of the compiled PYc file is different, 2.5 compiled PYC files, 2.4 version of Python is not executable. PYC files can also be deserialized, and different versions of the compiled PYC files are different.

3. String

String length acquisition: Len (str)
Letter handling:
All caps: Str.upper ()
All lowercase: str.lower ()
Case swap: Str.swapcase ()
Initial capitalization, remaining lowercase: str.capitalize ()
Initial capital: Str.title ()
The string goes to the space and goes to the specified character:
Go on both sides Space: Str.strip ()
Left space: Str.lstrip ()
Go right Space: Str.rstrip ()
Go to both sides of the specified character: Str.strip (' specified character '), corresponding to the Lstrip,rstrip
String judgments related to:
Whether to start with start: Str.startswith (' Start ')
End With end: Str.endswith (' End ')
Whether it is all letters or numbers: Str.isalnum ()
Full letter: Str.isalpha ()
Whether full number: Str.isdigit ()
Full lowercase: str.islower ()
All caps: Str.isupper ()
String substitution Related:
Replace old with New:str.replace (' old ', ' new ') #默认全替换
Replace the specified number of times with old as New:str.replace (' old ', ' new ', replacement number)
String Search Related:
Search for specified string, no return -1:str.find (' t ')
Specify starting Position search: Str.find (' t ', start)
Specify start and end position search: Str.find (' t ', start,end)
Search from right: Str.rfind (' t ')
Number of specified strings searched: Str.count (' t ')
All of the above methods can be replaced with index, the difference is to use the index to find not to throw an exception, and find returns-1
Str.center (width[, Fillchar]):
Width-This is the total width of the string.
Fillchar-This is the padding, not the default is a space.
Str.capitalize ():
The capitalize () method returns a copy of the string, with only its first letter capitalized.
Join method:
Join method for connecting string arrays
Cases:
s = [' A ', ' B ', ' C ', ' d ']
print '. Join (s)
print '-'. Join (s)

4.

Create a list
Sample_list = [' A ', 1, (' A ', ' B ')]

Python list Operations
Sample_list = [' A ', ' B ', 0,1,3]

To get a value from a list
Value_start = sample_list[0]
End_value = Sample_list[-1]

Delete the first value of a list
Del Sample_list[0]

Insert a value in the list
SAMPLE_LIST[0:0] = [' Sample value ']

Get the length of the list
List_length = Len (sample_list)

List traversal
For element in Sample_list:
Print (Element)

Python list advanced Operations/Tips

Produces a numeric increment list
Num_inc_list = Range (30)
#will return a list [0,1,2,..., 29]

Initialize a list with a fixed value
Initial_value = 0
List_length = 5
Sample_list = [Initial_value for i in range (10)]
Sample_list = [Initial_value]*list_length
# sample_list ==[0,0,0,0,0]


Attached: Python built-in type
1, List: Lists (that is, dynamic arrays, C + + standard library vector, but can contain different types of elements in a list)
A = ["I", "You", "he", "she"] # elements can be of any type.

Subscript: Read and write by subscript, as array processing
Starting with 0, negative subscript usage
0 first element, 1 last element,
-len first element, len-1 last element
Number of elements to fetch list
Len (list) #list的长度. The actual method is the __len__ (self) method that called the object.

Create continuous list
L = range (1,5)       #即 l=[1,2,3,4], with no last element
L = range (1, 2) #即 l=[1, 3, 5 , 7, 9]

Method of List
L.append (Var) #追加元素
L.insert (Index,var)
L.pop (Var) #返回最后一个元素 and removed from the list
L.remove (Var) #删除第一次出现的该元素
L.count (Var) #该元素在列表中出现的个数
L.index (Var) #该元素的位置, no exception thrown
L.extend (list) #追加list, that is, merge list to L
L.sort () #排序
L.reverse () #倒序
List operator:, +,*, Keyword del
A[1:] #片段操作符, for the extraction of sub-list
[1,2]+[3,4] #为 [1,2,3,4]. With Extend ()
[2]*4 #为 [2,2,2,2]
Del L[1] #删除指定下标的元素
Del L[1:3] #删除指定下标范围的元素
Copy of List
L1 = L #L1为L的别名, in C is the same pointer address, the L1 operation is the operation of L. This is how the function arguments are passed.
L1 = l[:] #L1为L的克隆, that is, another copy.

List comprehension
[<expr1> for K in L if <expr2>]

5. Dictionary operation


Radiansdict.clear (): Delete all elements in the dictionary
Radiansdict.copy (): Returns a shallow copy of a dictionary
Radiansdict.fromkeys (): Creates a new dictionary with the key of the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary
Radiansdict.get (Key, Default=none): Returns the value of the specified key if the value does not return the default value in the dictionary
Radiansdict.has_key (Key): Returns False if the key returns true in the dictionary Dict
Radiansdict.items (): Returns an array of traversed (key, value) tuples in a list
Radiansdict.keys (): Returns a dictionary of all keys in a list
Radiansdict.setdefault (Key, Default=none): Similar to get (), but if the key does not already exist in the dictionary, the key will be added and the value will be set to default
Radiansdict.update (DICT2): Update the dictionary dict2 key/value pairs to Dict
Radiansdict.values (): Returns all values in the dictionary as a list

Homework: Small program to implement shopping, support multi-user login, can recharge and buy multiple times

#/usr/bin/env Python3
#coding: Utf-8

Import Os,json
Import time


def login (): #用户登陆函数
Shop = [#商品店
("Bike", 1000),
("Coffe", 30),
("Alineware", 16000),
("ThinkPad", 8000),
("iphone", 7000),
]
Storage_user_file = "./user.py" #存放用户名, a Dictionary of passwords and balances, stored in JSON format {"Wyx": ["Jerry", "100000"]}
User_login_num = 0
Exit_flag = True #退出程序标志位
While Exit_flag:
Existing_users_dict = json.load (open (Storage_user_file, ' R ')) #读取用户资料, stored as a dictionary
Get_user = input ("Please your username")
Get_pass = input ("Please your password")
If Get_user in existing_users_dict and get_pass = = Existing_users_dict[get_user][0]: #如果用户名密码正确
Print ("Welcome to login..")
Shop_car = {} #存储购买商品的名称以及商品的价格及和个数 "bike": [100,8]
Salary = existing_users_dict[get_user][1] #获取当前用户的工资
Salary=int (Salary)
While Exit_flag:
For item in enumerate: #在shop列表里的每个元组前加上序号, changed to (1, ("Bike", 100))
S_index = item[0] #每个元组的的序号
S_name = item[1][0] #商品
S_price = item[1][1] #商品的价格
Print (S_index,s_name,s_price) #输出商店里面 the label of the product, the name of the product, and the price of the product
Produc = input ("Please select the item you want to buy Q=quit,c=check")
If Produc.isdigit (): #如果商品的标号以及购买的个数为整形
Producnum = input ("Please enter the number of purchases")
producnum = Int (producnum)
produc = Int (produc)
If Produc*producnum < salary: #如果购买的商品个数小于工资
P_product = Shop[produc] #商品以及对应的价格, for tuples (' ThinkPad ', 8000)
P_product_name = p_product[0] #商品的名称
P_product_price = p_product[1] #商品的价格
Salary = Salary-p_product_price*producnum #工资等于工资减去购买的商品价格乘商品个数
If STR (salary). IsDigit ():
EXISTING_USERS_DICT[GET_USER][1] = Salary #在字典做出相应的更改, write the remaining wages
Shop_car[p_product_name] = [P_product_price,producnum] #把购买的物品和价格以及购买数量放到购物车
Buying_time = Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())
LISTNUM = Len (Existing_users_dict[get_user]) #查看这个用户是否第一次购买
if ListNum = = 2:
Existing_users_dict[get_user].append ({}) #改变初始字典结构为 {' Wyx ': [' Jerry ', 99910, {}]}
Existing_users_dict[get_user][2][p_product_name]=[buying_time,producnum] #把购买时间写入到文件为 {' user ': [' password ', balance, {' Purchased item ': [' Purchase time ', Quantity]}]}
Print (existing_users_dict)
Json.dump (Existing_users_dict,open (Storage_user_file, "w")) #把剩余的钱存入到文件
Print ("You have purchased%s at%s, balance is%s"% (p_product,producnum,salary))
Else
Existing_users_dict[get_user][2][p_product_name]=[buying_time,producnum] #把购买时间写入到文件为 {' user ': [' password ', balance, {' Purchased item ': [' Purchase time ', Quantity]}]}
Json.dump (Existing_users_dict,open (Storage_user_file, "w")) #把剩余的钱存入到文件
Print ("You have purchased%s at%s, balance is%s"% (p_product,producnum,salary))
Else
Recharge = input ("Insufficient balance, whether to recharge Y or n")
if recharge = = ' Y ' or ' yes ':
Recharge_num = input ("Please enter a recharge number")
recharge_num = Int (recharge_num)
Salary = Salary+recharge_num #最新的余额为之前的余额加上充值的余额
EXISTING_USERS_DICT[GET_USER][1] = Salary #把最新的余额存入字典
Print ("The balance after the reload is%s"% salary)
elif Recharge = = ' n ':
Print (' Insufficient balance ')
Else
Print ("Input wrong, please re-enter")
Else
Recharge = input ("Insufficient balance, whether to recharge Y or n")
if recharge = = ' Y ':
Recharge_num = input ("Please enter a recharge number")
recharge_num = Int (recharge_num)
Salary = Salary+recharge_num #工资等于余额加上充值的钱
EXISTING_USERS_DICT[GET_USER][1] = Salary #改变字典里面的钱
Json.dump (Existing_users_dict,open (Storage_user_file, "w")) #把剩余的钱存入到文件
Print ("The balance after the reload is%s"% salary)
elif Recharge = = ' n ':
Print ("Insufficient balance")
Else
Print ("Input wrong, please re-enter")
Elif Produc = = ' Q ': #如果用户输入退出键
Print ("Items you have purchased". Center (40, '-'))
For I in Shop_car:
Produc_price = shop_car[i][0] #本次购物车里的商品价格
Produc_num = shop_car[i][1] #本次购物车里面的购物次数
Print ("The item you purchased this time is:%s Price:%s number is%s"% (I,produc_price,produc_num))
Print ("END". Center (40, "-"))
Print ("Your remaining salary is%s \ n"% salary)
Exit_flag = False
Elif Produc = = ' C ':
Buy_produc_num = Len (Existing_users_dict[get_user]) #查看是否第一次购物
if Buy_produc_num = = 2:
Print ("You have not purchased the product, please continue to purchase")
Else
Print ("Items you purchased". Center (40, ' * '))
Buy_produc = existing_users_dict[get_user][2] #用户购买的物品包括购买时间和数量
For Producname in Buy_produc:
Buy_produc_name = Producname #物品价格
Buy_produc_time = buy_produc[producname][0] #购买时间
Buy_producnum = buy_produc[producname][1] #购买数量
Print ("The item you purchased is:%s Time:%s Number:%s"% (Buy_produc_name,buy_produc_time,buy_producnum))
Print ("END". Center (40, "*"))
Print ("Your remaining salary is%s \ n"% salary)
Else
Print ("Input wrong, please re-enter")
Else
If user_login_num>3:
Print ("You are locked")
Exit_flag = False
Else
User_login_num+=1
Print ("Please continue to try")

if __name__ = = ' __main__ ':
Login ()

Data types of Python learning

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.