使用 "bitwise or" 运算符附加列表的系列元素
Appending series elements of a list using the "bitwise or" operator
基本上我有一个列表,其中每个元素都是一个系列,并且列表是任意长的。我想知道如何以创建变量 matches = listerino[0] | listerino[1] | ... | listerino[len(listerino)]
.
的方式遍历列表
到目前为止,我最接近上述情况的是:
matches = pd.Series()
for t in range(0, len(listerino)-1, 2):
x = listerino[t] | listerino[t+1]
matches = matches | x
但是,正如您可能看到的那样,这仅适用于偶数长度列表,因为它错过了奇数长度列表的最后一个元素。此外,我不得不将匹配定义为首先等于一个空系列,然后附加到 x,有更好的方法吗?
谢谢
为什么不使用 |=
运算符?
matches = None
for series in listerino:
# base case:
if matches is None:
matches = series
else:
matches |= series
这相当于matches = matches | series
您尝试执行的此操作通常称为 "reduction",可以通过 functools.reduce
:
完成
import functools
import operator
matches = functools.reduce(operator.or_, listerino)
operator
module conveniently defines the operator.or_
函数,它有两个输入和 returns x | y
。
基本上我有一个列表,其中每个元素都是一个系列,并且列表是任意长的。我想知道如何以创建变量 matches = listerino[0] | listerino[1] | ... | listerino[len(listerino)]
.
到目前为止,我最接近上述情况的是:
matches = pd.Series()
for t in range(0, len(listerino)-1, 2):
x = listerino[t] | listerino[t+1]
matches = matches | x
但是,正如您可能看到的那样,这仅适用于偶数长度列表,因为它错过了奇数长度列表的最后一个元素。此外,我不得不将匹配定义为首先等于一个空系列,然后附加到 x,有更好的方法吗?
谢谢
为什么不使用 |=
运算符?
matches = None
for series in listerino:
# base case:
if matches is None:
matches = series
else:
matches |= series
这相当于matches = matches | series
您尝试执行的此操作通常称为 "reduction",可以通过 functools.reduce
:
import functools
import operator
matches = functools.reduce(operator.or_, listerino)
operator
module conveniently defines the operator.or_
函数,它有两个输入和 returns x | y
。