Python dictionary 課堂筆記整理

2021-10-05 16:11:21 字數 2651 閱讀 5796

dictionaries are like bags - no order

purse =

dict()

purse[

'money']=

12purse[

'candy']=

3purse[

'tissues']=

75print

(purse)

# print

(purse[

'candy'])

# 3purse[

'candy'

]= purse[

'candy']+

2print

(purse)

#

1.the get method for dictionaries

if name in counts:

x = counts[name]

else

: x =

0

可以被替代為:

//如果counts中存在name的key,那麼返回它的value,否則返回0

x = counts.get(name,

0)

2.計數

counts =

dict()

names =

['csev'

,'cwen'

,'csev'

,'zqian'

,'cwen'

]for name in names :

counts[name]

= counts.get(name,0)

+1# if name not in counts :

# counts[name] = 1

# else :

# counts[name] = counts[name] + 1

print

(counts)

#

3.結合list

counts =

dict()

line =

input

('enter a line of text:'

)words = line.split(

)#預設以space為分隔符

print

('words:'

, words)

print

('counting...'

)for word in words:

counts[word]

= counts.get(word,0)

+1print

('counts'

, counts)

4.dictionary和for

counts =

for key in counts:

print

(key, counts[key]

)#for迴圈裡同時有兩個變數

#for aaa, bbb in counts.items() :

# print(aaa, bbb)

# chuck 1

# fred 42

# jan 100

5.dictionary轉化為list

jjj =

print

(list

(jjj)

)# ['jan', 'chuck', 'fred']

print

(jjj.keys())

# ['jan', 'chuck', 'fred']

print

(jjj.values())

# [100, 1, 42]

print

(jjj.items())

# [('jan', 100), ('chuck', 1), ('fred', 42)]

6.綜合前面所學知識點的乙個小實踐

統計txt檔案中最長出現的word並說出出現的次數

name =

input

('enter file:'

)handle =

open

(name)

#統計共有幾種word,以及它們出現的次數

counts =

dict()

for line in handle:

words = line.split(

)for word in words:

counts[word]

= counts.get(word,0)

+1#統計最長出現的word以及它的次數

bigcount =

none

bigword =

none

for word, count in counts.items():

#注意.items()不要漏掉哦!

if bigcount is

none

or count > bigcount:

bigword = word

bigcount = count

#輸出print

(bigword, bigcount)

sqlplus課堂筆記

desc user tables select from user tables where table name emp update 表名 set 列名 修改後資料 where 行名 aaa create table student id number 5,2 primary key,sname...

linux課堂筆記

rw r r 第一位有 d,l 表示普通檔案,d表示目錄,l表示連線檔案 快捷方式 接下來三位為一組,分別表示u所有者,g所屬組,o其他人。r讀,w寫,x執行 代表acl許可權 數字代表引用計數 開頭的檔案代表隱藏檔案 系統檔案 ls l簡稱ll就是ls的詳細資訊 建立目錄 mkdir make d...

課堂筆記六

偵錯程式 gdb 程式除錯工具 使用 gcc g test.c o test gdb test gdb run 執行程式 gdb list 檢視 gdb quit 退出 gdb break 21 執行到21行 gdb next 單步執行 gdb print 變數名 檢視變數數 gdb continu...