python tuple 元組問(wèn)題

  1. 一個(gè)元組的多元素賦值可以寫(xiě)或不寫(xiě)括號(hào),最好還是寫(xiě)括號(hào),比較好記。但是單個(gè)元素賦值一定要加括號(hào)和逗號(hào),不然會(huì)識(shí)別為字符串str。
  2. 比較神奇的是,這東西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'>
  1. 記錄一下“一行賦值加累加”的代碼,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ù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、python 變量和數(shù)據(jù)類(lèi)型 1.整數(shù) Python可以處理任意大小的整數(shù),當(dāng)然包括負(fù)整數(shù),在Python程序...
    績(jī)重KF閱讀 2,019評(píng)論 0 1
  • 0. 序言 python 是一門(mén)腳本語(yǔ)言:封裝性強(qiáng),語(yǔ)法簡(jiǎn)潔,開(kāi)發(fā)效率高,只用函數(shù)open就可以打開(kāi)一個(gè)txt文件...
    付凱強(qiáng)閱讀 1,334評(píng)論 0 5
  • 本節(jié)要介紹的是Python里面常用的幾種數(shù)據(jù)結(jié)構(gòu)。通常情況下,聲明一個(gè)變量只保存一個(gè)值是遠(yuǎn)遠(yuǎn)不夠的,我們需要將一組...
    小黑y99閱讀 65,607評(píng)論 0 9
  • 這漆黑的夜色, 唯一能給人溫暖就是星。 點(diǎn)點(diǎn)星光照亮前行的路, 伴著星我進(jìn)去夢(mèng)鄉(xiāng), 他是會(huì)說(shuō)話的眼睛, 帶著我陷入...
    慶小冬閱讀 391評(píng)論 2 9
  • “來(lái),干了這一杯?!卑w是化學(xué)課代表,拿出試管給每人倒了100ml。 一晚上的斗地主,我把這月的生活費(fèi)輸光了。 “...
    伊三弄閱讀 585評(píng)論 0 3

友情鏈接更多精彩內(nèi)容