Python90-6 使用解包替代索引

第6条:使用解包替代索引

Item 6: Prefer Multiple Assignment Unpacking Over Indexing

Python内置的tuple可以创建不变的、有序序列。

在下面简单的例子中,tuple存放一对值(key,value),来自一个字典的键值对。

snack_calories = {
    'chips'140,
    'popcorn'80,
    'nuts'190,
}
items = tuple(snack_calories.items())
print(items)
# (('chips', 140), ('popcorn', 80), ('nuts', 190))

tuple中的值可用索引访问(不使用解包):

item = ('Peanut butter''Jelly')
first = item[0]
second = item[1]
print(first, 'and', second)
# Peanut butter and Jelly

tuple一旦创建不可修改。

pair = ('Chocolate''Peanut butter')
pair[0] = 'Honey' # Wrong 

python有一种语法叫解包(unpacking),允许多个赋值。可以用解包替代索引方式取tuple中的值。

item = ('Peanut butter', 'Jelly')
first, second = item  # 解包(Unpacking)
print(first, 'and', second)

解包通常比索引方式更简洁,解包在lists,sequences,多级迭代上可用。多级解包方式可运行但不推荐。

favorite_snacks = {
    'salty': ('pretzels'100),
    'sweet': ('cookies'180),
    'veggie': ('carrots'20),
}
((type1, (name1, cals1)),
 (type2, (name2, cals2)),
 (type3, (name3, cals3))) = favorite_snacks.items()
print(f'Favorite {type1} is {name1} with {cals1} calories')
print(f'Favorite {type2} is {name2} with {cals2} calories')
print(f'Favorite {type3} is {name3} with {cals3} calories')

Python新手可能对解包用来原地交换而不需要额外变量感到惊讶。一般的交换需要额外变量temp。例如下面的冒泡排序,下面是一般写法(类似C语言写法)

def bubble_sort(a):
    for _ in range(len(a)):
        for i in range(1len(a)):
            if a[i] < a[i-1]:
                temp = a[i]
                a[i] = a[i-1]
                a[i-1] = temp
names = ['pretzels''carrots''arugula''bacon']
bubble_sort(names)
print(names)

而使用解包,只需要一行就可以完成交换。

def bubble_sort(a):
    for _ in range(len(a)):
        for i in range(1len(a)):
            if a[i] < a[i-1]:
                a[i-1], a[i] = a[i], a[i-1]  # 交换a[i-1],a[i]

右侧a[i], a[i-1]会先计算,然后将值放入一个临时tuple中,然后进行解包,赋值给左侧的a[i-1], a[i]。最后,释放临时tuple。

解包也可以应用在for循环或类似的东西(如推导式和生成器表达式)来简化代码。不使用解包:

snacks = [('bacon'350), ('donut'240), ('muffin'190)]
for i in range(len(snacks)):
    item = snacks[i]
    name = item[0]
    calories = item[1]
    print(f'#{i+1}{name} has {calories} calories')

使用enumerate和解包:

for rank, (name, calories) in enumerate(snacks, 1):
    print(f'#{rank}{name} has {calories} calories')

注:enumerate会在下一节讲到。它会返回一个迭代器。每个元素是一个元组(计数值,迭代对象)

这就是Pythonic的循环写法:简短易读,通常不需要使用索引。Python为list结构提供了更多解包功能(后面的章节介绍)。合适地使用解包可避免索引,使代码简洁易读。

Things to Remember

  • • Python有一种特殊语法叫解包(unpacking),可在一个语句内进行多个赋值。

  • • 解包在Python中被泛化,可以用于任意可迭代对象,包括多级可迭代对象。

  • • 通过解包避免索引,可以减少多余,提升可读性。


原文始发于微信公众号(一只大鸽子):Python90-6 使用解包替代索引

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/237482.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!