- Functional Python Programming
- Steven F. Lott
- 239字
- 2021-08-27 19:20:29
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)))
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.
- Vue.js設(shè)計(jì)與實(shí)現(xiàn)
- LabVIEW 2018 虛擬儀器程序設(shè)計(jì)
- Python數(shù)據(jù)分析(第2版)
- 深度學(xué)習(xí):算法入門與Keras編程實(shí)踐
- 實(shí)戰(zhàn)Java高并發(fā)程序設(shè)計(jì)(第3版)
- Building RESTful Python Web Services
- Learning OpenStack Networking(Neutron)(Second Edition)
- Unity 2018 Shaders and Effects Cookbook
- Scala編程實(shí)戰(zhàn)
- Android Studio Cookbook
- INSTANT Apache Hive Essentials How-to
- Python應(yīng)用開發(fā)技術(shù)
- The Applied Data Science Workshop
- AI輔助編程Python實(shí)戰(zhàn):基于GitHub Copilot和ChatGPT
- Python編程基礎(chǔ)與數(shù)據(jù)分析