rus*_*ro1 3 python list unpack python-3.x iterable-unpacking
我试图找出在列表中解包迭代器的pythonic方法是什么。
例如:
my_iterator = zip([1, 2, 3, 4], [1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)
我提供了以下几种在列表中解压缩迭代器的方法:
1)
my_list = [*my_iterator]
Run Code Online (Sandbox Code Playgroud)
2)
my_list = [e for e in my_iterator]
Run Code Online (Sandbox Code Playgroud)
3)
my_list = list(my_iterator)
Run Code Online (Sandbox Code Playgroud)
No 1)是我最喜欢的方法,因为它减少了代码,但是我想知道这是否也是pythonic方法。或者,也许除了Python 3之外,还有另一种方法可以实现这一目标?
在探索了更多主题之后,我得出了一些结论。
应该有一种——最好只有一种——明显的方法来做到这一点
(蟒蛇之禅)
决定哪个选项是“pythonic”应该考虑一些标准:
在所有标准中获胜的明显“pythonic”选项是选项编号 3):
列表 = 列表(my_iterator)
这就是为什么“明显”没有 3) 是 pythonic 的原因:
选项 1)(使用 * 解包)星号运算符如果您不经常使用它可能会有点混乱,在 Python 中使用星号有4 种情况:
另一个很好的论点是python 文档本身,我做了一些统计来检查文档选择了哪些选项,为此我选择了 4 个内置迭代器和模块itertools 中的所有内容(使用如下:)itertools.
来看看如何它们被解压到一个列表中:
在浏览文档后,我发现:使用选项 1) 和 2) 在列表中解压了 0 个迭代器,使用选项 3) 解压了 35 个迭代器。
结论:
在列表中解压迭代器的 Pythonic 方法是:
my_list = list(my_iterator)
虽然解包运算符*
不常用于将单个可迭代对象解包到列表中(因此[*it]
可读性比 稍差list(it)
),但在其他几种情况下它很方便且更具 Python 风格:
mixed_list = [a, *it, b]
Run Code Online (Sandbox Code Playgroud)
这比
mixed_list = [a]
mixed_list.extend(it)
mixed_list.append(b)
Run Code Online (Sandbox Code Playgroud)
mixed_list = [*it1, *it2, a, b, ... ]
Run Code Online (Sandbox Code Playgroud)
这与第一种情况类似。
first, *rest = it
Run Code Online (Sandbox Code Playgroud)
it
这会提取into的第一个元素first
并将其余元素解压到列表中。甚至可以做
_, *mid, last = it
Run Code Online (Sandbox Code Playgroud)
这会将 的第一个元素转储it
到无关变量 中_
,将最后一个元素保存到 中last
,并将其余元素解压到列表中mid
。
it = (0, range(5), 3)
a1, (*a2,), a3 = it # Unpack the second element of it into a list a2
e1, (first, *rest), e3 = it # Separate the first element from the rest while unpacking it[1]
Run Code Online (Sandbox Code Playgroud)
这也可以用在for
语句中:
from itertools import groupby
s = "Axyz123Bcba345D"
for k, (first, *rest) in groupby(s, key=str.isalpha):
...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
576 次 |
最近记录: |