使用“按位或”运算追加列表的系列元素

2024-10-01 15:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我有一个列表,其中每个元素都是一个序列,列表任意长。我想知道如何遍历这个列表,这样我就可以创建一个变量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上,有没有更好的方法?你知道吗

谢谢


Tags: in元素列表forlen定义range序列
2条回答

您尝试执行的此操作通常称为“还原”,可以通过^{}完成:

import functools
import operator

matches = functools.reduce(operator.or_, listerino)

^{} module方便地定义了^{}函数,它接受两个输入并返回x | y。你知道吗

为什么不使用|=运算符?你知道吗

matches = None
for series in listerino:
    # base case:
    if matches is None:
        matches = series
    else:
        matches |= series

这相当于matches = matches | series

相关问题 更多 >

    热门问题