1.数据结构和算法
1.8与字典有关的计算问题
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
#zip()的结果只能使用一次
min_price = min(zip(prices.values(), prices.keys()))
min_price1 = min(prices, key = lambda s: prices[s])
1.9在两个字典中寻找相同点
a = {
'x': 1,
'y': 2,
'z': 3
}
b = {
'w': 10,
'x': 11,
'y': 2
}
a.keys() &b.keys()
a.keys() - b.keys()
a.items() & b.items()
1.10从序列中移除重复项且保持元素间的顺序不变
#序列中的元素是可哈希的,即在生命周期不可变
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
a = [1, 5, 2, 1, 9, 1, 5, 10]
print(list(dedupe(a)))
#不可哈希的对象
def dedupe1(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
1.11对切片命名
#创建切片对象
items = [0, 1, 2, 3, 4, 5, 6]
a = slice(2, 4)
print(items[2:4])
print(items[a])
items[a] = [10, 11]
del items[a]
#有start, stop,step属性
a.start
a.stop
a.step
#indices()将切片映射到特定大小的序列上
b = slice(2, 50, 2)
s = 'HelloWorld'
print(b.indices(len(s)))
1.12找出序列中出现次数最多的元素
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
;the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
1.13通过公共间对字典列表排序
rows = [
{'fname': 'Brian', 'lname': 'Jones, 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid':1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]
from operator import itemgetter
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_uid = sorted(rows, key=itemgetter('uid'))
rows_by_flname = sorted(rows, key=itemgetter('fname', 'lname'))
1.14对不原生支持比较操作的对象排序
class User:
def __init__(self, user_id):
self.user_id = user_id
def __repr__(self):
return 'User({})'.format(self.user_id)
users = [User(23), User(3), User(99)]
print(sorted(users, key=lambda s: s.user_id))
from operator import attrgetter
print(sorted(users, key=attrgetter('user_id'))
本文探讨了Python中字典和序列的高级操作,包括如何处理字典中的计算问题,如寻找最小值;如何在两个字典中找到共同点;如何去除序列中的重复项并保持原有顺序;如何对切片进行命名;如何找出序列中出现频率最高的元素;以及如何对字典列表进行排序。这些技巧对于提升Python编程效率至关重要。
294

被折叠的 条评论
为什么被折叠?



