- 一個(gè)元組的多元素賦值可以寫(xiě)或不寫(xiě)括號(hào),最好還是寫(xiě)括號(hào),比較好記。但是單個(gè)元素賦值一定要加括號(hào)和逗號(hào),不然會(huì)識(shí)別為字符串str。
- 比較神奇的是,這東西tuple竟然可以是空的。但它又不能改,暫時(shí)沒(méi)想到咋用。
# tuple with multiple values
>>> t = 'a', 'b', 'c', 'd', 'e'
>>>type(t)
<class 'tuple'>
>>> t1 = 'a', 'b', 'c', 'd', 'e'
>>>type(t1)
<class 'tuple'>
# tuple with a single value
>>>t2 = ('a',)
>>>type(t2)
<class 'tuple'>
>>>t3 = ('a')
>>>type(t3)
<class 'str'> ### this is a string
# an empty tuple with no value
>>>t4 = ()
>>>type(t4)
<class 'tuple'>
- 記錄一下“一行賦值加累加”的代碼,get+tuple+初始值。馬克一下py4e的作業(yè)。
# open a file
# name = input("Please Enter filename:")
name = 'mbox-short.txt'
if len(name) < 1 : name = "mbox-short.txt"
try:
handle = open(name)
except:
print('Please input the correct filename')
# print the hours and email counts
hour_count = dict()
for line in handle:
if line.startswith('From '):
words_of_line = line.strip().split()
hours = words_of_line[5][0:2]
hour_count[hours] = 1 + hour_count.get(hours,0)
hour_count = sorted([(k,v) for k,v in hour_count.items()])
for k,v in hour_count:
print(k,v)
# print(hours) the hours were correct
# sum the counts
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。