您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页序列

序列

来源:二三娱乐

原文第2章第3节

分解序列(sequence unpacking)

The pattern of binding multiple names to multiple values in a fixed-length sequence。
序列中各值赋予不同变量名。

>>> pairs = [[1, 2], [2, 2], [2, 3], [4, 4]]

>>> same_count = 0

如果执行下列代码:

>>> for x, y in pairs:
        if x == y:
            same_count = same_count + 1

就可以得到:

>>> same_count
2

列表推导式(list comprehension)

An expression that can performs such a sequence processing operation which can be expressed by evaluating a fixed expression for each element in a sequence and collecting the resulting values in a result sequence.
一行代码直接完成对列表的便利操作并返回值。
例如,

>>> odds = [1, 3, 5, 7, 9]
>>> [x+1 for x in odds]
[2, 4, 6, 8, 10]

# Another Example
>>> [x for x in odds if 25 % x == 0]
[1, 5]

通式:

[<map expression> for <name> in <sequence expression> if <filter expression>]

列表推导式的效果也可以用高阶函数的方式来达到,但前者更为常见(个人觉得前者更利于理解)。

数据类型的闭合性

In general, a method for combining data values has a closure property if the result of combination can itself be combined using the same method.
例如,列表自身可以组成列表的元素。

其它

  • 也是一种列表。

本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。

热门图文

Copyright © 2019-2025 yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务