Python程式設計中的幾個tips

2021-09-14 05:15:57 字數 2242 閱讀 1826

1. 在大數字中使用下劃線,增強**可讀性

#普通**

num1=100000000000

num2=100000000

res=num1+num2

print(res)

#使用下劃線 (適用於python3以上)

num1=1000_0000_0000

num2=1_0000_0000

res=num1+num2

print(res)

print(f'')
2. python的「三目運算子」
#普通**

condition=true

if condition==true:

x=1else:

x=0

# 使用「三目運算子」 

condition=true

x=1 if condition else 0

3. 使用enumerate
#普通**

names=['jerry','tom','alice','herry']

index=0

for name in names:

print(index,name)

index+=1

#使用enumerate

names=['jerry','tom','alice','herry']

for index,name in enumerate(names,start=1):

print(index,name)

4. 使用zip
#普通**

names=['jerry','tom','alice','herry']

scores=[99,89,79,69]

for index,name in enumerate(names):

score=scores[index]

print(str(name)+ "\'s score is" +str(score))

#使用zip

names=['jerry','tom','alice','herry']

scores=[99,89,79,69]

for name,score in zip(names,scores):

print(str(name)+ "\'s score is" +str(score))

5. unpack

『序列』解包,可以將python的可迭代物件中的元素,單個或多個的分離出來,

#分離元組中的每個元素

a,b,_=(1,2,3)

print(a)

print(b)

#使用*號分離多個元素

a,b,*c=(1,2,3,4,5,6)

print(a)

print(b)

print(c)

a,b,*_,d=(1,2,3,4,5,6)

print(a)

print(b)

print(c)

print(d)

6. setattr & getattr
class animal():

pass

animal=animal()

animal_list=

for key,value in animal_list.items():

setattr(animal,key,value)

for key in animal_list.keys():

print(getattr(animal,key))

7.使用getpass 輸入密碼
#使用input

username=input("username:")

password=input("password:")

print("log in...")

print(password)

#使用getpass

from getpass import getpass

username=input("username:")

password=getpass("password:")

print("log in...")

print(password)

幾個加速Swift開發的小tip

又是周五了,週末不要浪,一起學點swift!本週再次為大家帶來了一些swift的小技巧,都是些奇淫巧計,不知道也無妨,但swift最吸引我的一點就是它的簡潔易用。主要內容有 private set 語法 分號的使用 利用string型別初始化方法簡化uitableviewcell的reuseiden...

Python 程式設計中遇到的幾個小問題

1.引入同級目錄下的 py中的sss類 直接在要引入的py檔案中 import 或者 from import sss 2.arg 在python的函式用 def fun args join args print arg arg是乙個tuple type args 錯誤,一次給type傳遞了3個引數 ...

程式設計中的幾個原則

程式設計中的幾個原則 注 使用設計模式其實就是對以下準則的貫徹和落實 一 ocp法則 開閉法則 open closed principle 乙個軟體系統應當對擴充套件開放,對修改關閉 優點 原則的描述就是其優點所在,1 通過擴充套件已有軟體系統,可以提供新的行為,以滿足對軟體的新的需求,使變化中的軟...