【工程類】【python】python筆記

1、有序字典OrderedDict

有時候,我們需要獲取輸入到字典中的順序,可以使用python自帶模塊中的OrderedDict。

栗子如下

from collections import OrderedDict

cars = OrderedDict()
cars["BMW"] = "50"
cars["tesla"] = "100"
cars["benz"] = "80"

for name,price in cars.items():
	print("car name is " + name + ", price is " + price)
"""print
car name is BMW,price is 50.
car name is tesla,price is 100.
car name is benz,price is 80.
"""

2、*args和**args的用法和區別

  • *args: 接收任意數量形參。
  • 舉個栗子,一個函數的功能是做菜,要求輸入菜名和其配料,但是配料非常多且不固定,那麼就可以這樣寫
def cook(food_name,*args):
	print("食物名字是:" + food_name)
	print("配料有:" + ' '.join(args))
cook(food_name="宮保雞丁","雞丁肉","蔥","黃瓜丁")

"""print
食物名字是:宮保雞丁
配料有:雞丁肉 蔥 黃瓜丁
"""

args是一個空元組,接受參數後爲(“雞丁肉”,“蔥”,“黃瓜丁”)。

  • **args:使用任意數量的關鍵字參數
  • 舉個栗子,一個收集用戶信息的函數,必須傳入的是姓名,其餘的需要根據需要進行傳入,則可以這樣寫
def collect(name,**args):
	print("姓名是:" + name)
	for k in args.items():
		print(k + ":" + args[k])
collect(name="張三",address="北京",tel="12456789")
"""print
姓名是:張三
address:北京
tel:123456789
"""

args是一個空字典,接收參數後爲{“address”:“北京”,“tel”:“123456789”}

3、for else 用法

有時候我們進行判斷時會用到這種方法

numbers =[1,2,3,4, 5]
is_odd_exist = False
for n in numbers:   
    if n % 2 == 1:
        is_odd_exist = True
        break
if is_odd_exist:  
    print('Odd exist')
else:   
    print('Odd not exist')

for…else…寫法

numbers =[1,2,3,4, 5]
for n in numbers:   
    if n % 2 == 1:
        print('Odd exist')
        break
else:
    print('Odd not exist')

4、python保留小數點位數

  • 對於浮點數
a=1.36852
a=round(a,2)
print a
#結果1.36
  • 對於整數
from decimal import Decimal
a=1
a=Decimal(a).quantize(Decimal('0.00'))
print a
#結果1.00
  • 通用方法
a=1
a=("%.2f" % a)
print a
#結果1.00

5、字符串加入變量

有時候,我們需要在字符串中加入相應的變量,以下提供了幾種字符串加入變量的方法:

  • +連字符
name = 'zhangsan'
print('my name is '+name)
#結果爲 my name is zhangsan
  • % 字符
name = 'zhangsan'
age = 25
price = 4500.225
print('my name is %s'%(name))
print('i am %d'%(age)+' years old')
print('my price is %f'%(price))
#保留指定位數小數(四捨五入)
print('my price is %.2f'%(price))

結果爲
my name is zhangsan
i am 25 years old
my price is 4500.225000
my price is 4500.23
  • format()函數
    對於變量較多的情況,加入加’+‘或者’%'相對比較麻煩,這種情況下可以使用format函數
name = 'zhangsan'
age = 25
price = 4500.225
info = 'my name is {my_name},i am {my_age} years old,my price is {my_price}'\
    .format(my_name=name,my_age=age,my_price=price)
print(info)

結果爲:
my name is zhangsan,i am 25 years old,my price is 4500.225

6、字典嵌套

在一些時候,我們經常需要對字典進行嵌套賦值,但是每次取出來還要判斷是否存在,所以我們希望有一種方法能夠方便的對字典進行初始化。。以下是字典嵌套初始化的方法。

def pack_data():
	dic = {}
	list1=[1,2,3]
	list2=[4,5,6]
	list3=[7,8,9]
	for layer1 in list1:
		dic[layer1] = {}.fromkeys(list2)
		for layer2 in list2:
			dic[layer1][layer2] = {}.fromkeys(list3)
			for layer3 in list3:
				dic[layer1][layer2][layer3]=5
	return dic
'''
得到的結果是:
{1: {4: {8: 5, 9: 5, 7: 5}, 
     5: {8: 5, 9: 5, 7: 5}, 
2:  {4: {8: 5, 9: 5, 7: 5}, 
     5: {8: 5, 9: 5, 7: 5}, 
3:  {4: {8: 5, 9: 5, 7: 5}, 
     5: {8: 5, 9: 5, 7: 5}, 
     6: {8: 5, 9: 5, 7: 5}}}
'''
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章