python工作中總結

來源:互聯網
上載者:User

標籤:命名   其它   style   email   類構造   定義   student   自動   同事   

以下方法平時很少用,用其它解決方案,只是總結了一些其它同事的技巧

  1   如何自動產生列表,加一個條件還能篩選

[x for x in range(10) if x>5 ]

來生一個字典試試

 

d = {x:randint(60,100) for x in range(1,21)}  //  randint需要匯入包   

from random import randint

用迭代篩選字典方法

{k:v for k,v in d.iteritems() if v>90}   // iteritems()  py3 也更名  

d.items()

如何用無組中每個元素命名

studen = ("xsy",16,"13575665","[email protected]")

這樣的資料存為元組節省記憶體,訪問時可以

#name

studen[0 ]

#age

studen[1]

以上方法訪問,但是代碼一多,數字代表什麼不夠直觀

python模仿c寫枚舉方法解決:1,先定義一些常量

NAME =0

AGE = 1

SEX = 2

EMAIL = 3

進階定義方法

NAME,AGE,SEX,EMAE = range(4)

 

以下舉例使用

//print(student[NAME])  // 

//if studen[AGE]>=18k

//if student[sex] == "male"

方法二,用類構造

from collections import namedtuple
student = namedtuple("student",[‘name‘,‘age‘,‘sex‘,‘xx‘])
s = student("jim",16,‘male‘,‘[email protected]‘)
print(s.name)
print(isinstance(s,tuple))//True,意思是可以用組的地方都 可以用這個方法





統記列表元素出現次數

from random import randint

[randint(0,20)for x in rnage(30)]//  將產生30個隨機數字  現在我們要統計成字典比如{8:2,7:6}   8出現2次,7出現6次。這樣子

d =[randint(0,20)for x in rnage(30)]、

最終成為

c= {2:6,6:4...........}

完成功能代碼如下

from random import randint
d =[randint(0,20) for x in range(30)]
c = dict.fromkeys(d,0)
for x in d:
c[x]+=1
print(c)

 

python工作中總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.