- 一个元组的多元素赋值可以写或不写括号,最好还是写括号,比较好记。但是单个元素赋值一定要加括号和逗号,不然会识别为字符串str。
- 比较神奇的是,这东西tuple竟然可以是空的。但它又不能改,暂时没想到咋用。
# 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的作业。
# 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