【问题标题】:Find the length of overalp in lists with binary values [duplicate]查找具有二进制值的列表中的重叠长度[重复]
【发布时间】:2021-06-22 11:20:04
【问题描述】:

假设我有这两个列表:

a = [1,0,0,0,1,1,1,1,1,1,1,1,0,0]

b = [0,0,0,0,1,1,1,0,0,0,1,1,0,0]

我想知道数字 1 出现在同一位置的次数,在这种情况下为 5

【问题讨论】:

  • 请向我们展示您到目前为止所做的尝试
  • 你可以和这两个列表,然后计算结果中的那些。
  • 还没有想到任何东西......建议是针对类似的问题,但他们想要两个列表中出现的值,这里我试图获取数字 ov相同且位置相同的值
  • 请从intro tour 重复on topichow to ask。 “我什么都想不出来”是问题分析中的问题,而不是 Stack Overflow 问题。我们希望您做出诚实的尝试,然后然后就您的算法或技术提出一个具体的问题。 Stack Overflow 无意取代现有的文档和教程。

标签: python arrays list


【解决方案1】:

将两个列表相加然后看每个单元格的结果是否为2(1 + 1):

a = [1,0,0,0,1,1,1,1,1,1,1,1,0,0]

b = [0,0,0,0,1,1,1,0,0,0,1,1,0,0]

sum = [] # sun of the two lists
for x in range(len(a)):
    sum.append(a[x] + b[x])

_1_in_both = []
for x in range(len(sum)):
    if sum[x] == 2: # sum[x] == 2 <==> 1 in both lists
        _1_in_both.append(x)

print('1 occurs in both lists', len(_1_in_both), 'times, in positions', _1_in_both)

输出:

1 在两个列表中出现 5 次,位置为 [4, 5, 6, 10, 11]

【讨论】:

    【解决方案2】:

    使用位运算符和 zip:

    sum([x&y for x,y in zip(a,b)])
    

    【讨论】:

      【解决方案3】:

      这是我在评论中的建议。

      import numpy as np
      
      a = [1,0,0,0,1,1,1,1,1,1,1,1,0,0]
      
      b = [0,0,0,0,1,1,1,0,0,0,1,1,0,0]
      
      result = np.logical_and(np.array(a), np.array(b))
      
      print(np.count_nonzero(result == True))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-07
        • 2014-05-08
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        • 2012-09-26
        相关资源
        最近更新 更多