官术网_书友最值得收藏!

Using reversed() to change the order

There are times when we need a sequence reversed. Python offers us two approaches to this: the reversed() function, and slices with reversed indices.

For example, consider performing a base conversion to hexadecimal or binary. The following code is a simple conversion function:

def digits(x: int, b: int) -> Iterator[int]:
if x == 0: return yield x % b for d in digits(x//b, b): yield d

This function uses a recursion to yield the digits from the least significant to the most significant. The value of x%b will be the least significant digits of x in the base b.

We can formalize it as follows:

In many cases, we'd prefer the digits to be yielded in the reverse order. We can wrap this function with the reversed() function to swap the order of the digits:

def to_base(x: int, b: int) -> Iterator[int]:
return reversed(tuple(digits(x, b)))
The reversed() function produces an iterable, but the argument value must be a sequence object. The function then yields the items from that object in the reverse order.

We can do a similar kind of thing with a slice, such as tuple(digits(x, b))[::-1]. The slice, however, is not an iterator. A slice is a materialized object built from another materialized object. In this case, for such small collections of values, the distinction is minor. As the reversed() function uses less memory, it can be advantageous for larger collections.

主站蜘蛛池模板: 阿勒泰市| 海丰县| 泌阳县| 萨嘎县| 镶黄旗| 涞水县| 七台河市| 大城县| 河曲县| 哈巴河县| 曲周县| 滦南县| 沙坪坝区| 鹿邑县| 邵东县| 武夷山市| 临漳县| 社旗县| 呼伦贝尔市| 衡阳县| 呼和浩特市| 武隆县| 二连浩特市| 凤冈县| 大洼县| 竹溪县| 兴隆县| 哈尔滨市| 蒲江县| 甘南县| 屯昌县| 集安市| 中牟县| 玉林市| 逊克县| 庐江县| 湘潭县| 德令哈市| 康保县| 济源市| 北海市|