#python学习笔记(十一)#元组:比较,排序,找出出现次数最多的单词

目录

1 Tuples are immutable

2 Comparing tuples

3 Tuple assignment

4 Dictionaries and tuples

5 Using tuples as keys in dictionaries

6 tuples VS list


1 Tuples are immutable

▲元组与列表类似,但是它不可改变

▲元组常用()括号表示

>>> t = ('a', 'b', 'c', 'd', 'e')

▲ 创建只包含一个元素的元组需要加逗号,否则认为是字符

>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>

>>> t2 = ('a')
>>> type(t2)
<type 'str'>

tuple()函数创建元组 ,如果tuple参数是一个序列(如字符串、列表或元组),tuple函数返回序列的各个元素组成的元组

>>> t = tuple()  ###tuple参数为空
>>> print(t)
()

>>> t = tuple('lupins')  ###tuple参数为字符串
>>> print(t)
('l', 'u', 'p', 'i', 'n', 's')


>>> lis=[1,2,3,4,5]  
>>> t=tuple(lis)   ###tuple参数为列表
>>> t
(1, 2, 3, 4, 5)

[ ]取出tuple中的元素,但由于不可变性,不能给元素赋新的值 

>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print(t[0])
'a'
>>> print(t[1:3])
('b', 'c')
>>> t[0] = 'A'
TypeError: object doesn't support item assignment

▲虽然tuple本身不可变,但可以生成一个新的tuple

>>> t = ('A',) + t[1:]
>>> print(t)
('A', 'b', 'c', 'd', 'e')

2 Comparing tuples

The comparison operators work with tuples and other sequences. Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next element, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big).

逐个比较,直到第一个不一样的,后续的不再比较

>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True

 ▲元组排序应用示例根据单词长度排序

txt = 'but soft what light in yonder window breaks'
words = txt.split()  ###拆分成单词

t = list()           ###创建空列表储存字符长度和字符内容
for word in words:
    t.append((len(word), word))   ###列表元素为元组,元组的第一项为单词长度,第二项为单词内容

t.sort(reverse=True)  ###列表排序,比较元组大小时从第一个开始比较(即字符长度)

res = list()              ###创建空字符储存结果
for length, word in t:    由于列表元素为元组,迭代变量两个分开表示
    res.append(word)      

print(res)

3 Tuple assignment

▲python可以给元组赋值,即可以同时值给多个变量

>>> m = [ 'have', 'fun' ]
>>> x, y = m
>>> x
'have'
>>> y
'fun'
>>>

▲当元组出现在=左边时,它被认为是变量的代号,而出现在右边时被认为是变量的值

>>> a='have'
>>> b='fun'
>>> a,b=b,a
>>> a
'fun'
>>> b
'have'

▲左右两边的元素数目要相同

>>> a, b = 1, 2, 3
ValueError: too many values to unpack

>>> a,b=1,[2,3]
>>> a
1
>>> b
[2, 3]

4 Dictionaries and tuples

▲字典的方法items将字典转化成key-value对元组

>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> print(t)
[('b', 1), ('a', 10), ('c', 22)]

▲生成列表后可以对其排序

>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> t
[('b', 1), ('a', 10), ('c', 22)]
>>> t.sort()
>>> t
[('a', 10), ('b', 1), ('c', 22)]

▲for循环遍历字典的keys和values 

for key, val in list(d.items()):
    print(val, key)

▲采用循环交换key和value从而实现对value的排序

>>> d = {'a':10, 'b':1, 'c':22}
>>> l = list()
>>> for key, val in d.items() :
... l.append( (val, key) )      ####交换key和value生成新列表
...
>>> l
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> l.sort(reverse=True)        ####列表排序,依据value排序
>>> l
[(22, 'c'), (10, 'a'), (1, 'b')]
>>>

▲示例:查找出现次数最多的单词

import string
fhand = open('romeo-full.txt') ###打开文件

###字典计数单词和次数
counts = dict()  
for line in fhand:
    line = line.translate(str.maketrans('', '', string.punctuation)) ###删除标点符号
    line = line.lower() ###全部变成小写
    words = line.split() ###每行分隔成单词
    for word in words:
        if word not in counts:
            counts[word] = 1
        else:
            counts[word] += 1 ###计数


###根据出现次数value排序
lst = list()
for key, val in list(counts.items()):
    lst.append((val, key)) ###交换key和value
    lst.sort(reverse=True) ###排序

for key, val in lst[:10]:
    print(key, val)

5 Using tuples as keys in dictionaries

▲示例:元组储存姓和名 ,生成电话簿字典

directory[last,first] = number ###创建字典

for last, first in directory:
    print(first, last, directory[last,first])  ###输出字典

6 tuples VS list

Because tuples are immutable, they don’t provide methods like sort and reverse, which modify existing lists. However Python provides the built-in functions sorted and reversed, which take any sequence as a parameter and return a new sequence with the same elements in a different order.

由于tuples的不可变性,作为返回值和函数参数更不容易出错

字典的keys只能是不可变的sequence,如strings或tuples

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值