PythonCookBook chapter-01-序列

(python3)

1,利用Counter从序列中找到出现次数最多的元素

from collections import Counter


names = ['leo', 'lily', 'lucy', 'leon', 'leo',
         'david', 'bool','leo', 'lily', 'lucy', 'leon']


name_cnt = Counter(names)
# 出现频率最高的三个
top_three = name_cnt.most_common(3)
print(top_three)
print('leon cnt:', name_cnt['leon'])


# 所有name的出现次数
all_item = name_cnt.most_common()
print(all_item)


# 将leon的次数减去2
name_cnt['leon'] -= 2
print(name_cnt.most_common())


# 利用update函数
words_cnt = Counter(names)
words_cnt.update(names)
print(words_cnt)

输出:

[('leo', 3), ('lily', 2), ('lucy', 2)]
leon cnt: 2
[('leo', 3), ('lily', 2), ('lucy', 2), ('leon', 2), ('david', 1), ('bool', 1)]
[('leo', 3), ('lily', 2), ('lucy', 2), ('david', 1), ('bool', 1), ('leon', 0)]
Counter({'leo': 6, 'lily': 4, 'lucy': 4, 'leon': 4, 'david': 2, 'bool': 2})

2,对字典列表排序

from operator import itemgetter

players = [{'name':'leo', 'uid':65, 'coin':9999, 'time':1232},
           {'name':'harry', 'uid':66, 'coin':999, 'time':1232},
           {'name':'mili', 'uid':55, 'coin':1999, 'time':1232},
           {'name':'tom', 'uid':58, 'coin':2999, 'time':1232}]

ret1 = sorted(players, key = itemgetter('name'))
for i in ret1:
    print(i)

print('------------------') 
ret2 = sorted(players, key=lambda r:(r['name'], r['uid']))
for i in ret2:
    print(i)

输出:

{'name': 'harry', 'uid': 66, 'coin': 999, 'time': 1232}
{'name': 'leo', 'uid': 65, 'coin': 9999, 'time': 1232}
{'name': 'mili', 'uid': 55, 'coin': 1999, 'time': 1232}
{'name': 'tom', 'uid': 58, 'coin': 2999, 'time': 1232}
------------------
{'name': 'harry', 'uid': 66, 'coin': 999, 'time': 1232}
{'name': 'leo', 'uid': 65, 'coin': 9999, 'time': 1232}
{'name': 'mili', 'uid': 55, 'coin': 1999, 'time': 1232}
{'name': 'tom', 'uid': 58, 'coin': 2999, 'time': 1232}

3,对象的排序

from operator import attrgetter

class Stud:
    def __init__(self, uid):
        self.uid = uid

    def __repr__(self):
        return 'Stud({})'.format(self.uid)

studs = [Stud(88), Stud(23), Stud(76), Stud(99)]
ret = sorted(studs, key = attrgetter('uid'))
for i in ret:
    print(i)
print('---------')
ret = sorted(studs, key = lambda r:r.uid)
for i in ret:
    print(i)

输出:

Stud(23)
Stud(76)
Stud(88)
Stud(99)
---------
Stud(23)
Stud(76)
Stud(88)
Stud(99)
4,筛选列表的元素
mylist = [99.0,88.0,68.5,79.5]

# 利用生成器
price = (val for val in mylist if val > 80)
print(price)
for i in price:
    print(i)

def is_valid(val):
    if val > 80:
        return True
    else:
        return False
# 利用内建的filter函数
price1 = list(filter(is_valid, mylist))
print(price1)

输出:

<generator object <genexpr> at 0x0000000002B6D9E8>
99.0
88.0
[99.0, 88.0]

猜你喜欢

转载自blog.csdn.net/vitas_fly/article/details/80236194
今日推荐