【问题标题】:Sequence of similar items in an array数组中相似项的序列
【发布时间】:2017-11-01 08:19:31
【问题描述】:

我是第一次使用 Python,我需要找到一种有效的方法来搜索三个、四个或五个元素的连续序列在更大的数组中是否相同。

例如:

array = [1, 0, 0, 0, 1]

输出:

number_same = 3
element = 0
positions = [1, 2, 3]

有什么建议或帮助吗?

谢谢!

【问题讨论】:

  • 序列应该是连续的?
  • 您的输出与输入不对应。
  • @KaushikNP 是的,确实,它应该是连续的。

标签: python arrays elements similarity


【解决方案1】:

以下行将为您提供一个值的元组列表及其在数组中的位置(按重复分组):

from itertools import groupby
[(k, [x[0] for x in g]) for k, g in groupby(enumerate(array), lambda x: x[1])]
>>> [(1, [0]), (0, [1, 2, 3]), (1, [4])]

您可以稍后过滤它以仅获得 3 次及以上的重复:

filter(lambda x: len(x[1])>2, grouped_array)

使用以下答案作为参考: What's the most Pythonic way to identify consecutive duplicates in a list?

【讨论】:

    【解决方案2】:

    我不太了解 Python,但我不认为有一个内置函数可以完成此操作。

    您可以遍历列表并使用第二个数组作为计数器。

    即如果位置 0 的数字是 1,则在第二个数组中的位置 1 上加 1

    original_array = [1, 0, 0, 0, 1]
    second_array_after_populating = [3, 2, 0, 0, 0]
    

    然后您只需扫描列表一次即可找到最常见的数字,以及该数字有多少。一旦你知道了这个数字,你就可以扫描原始列表以找到它出现的位置。

    【讨论】:

      【解决方案3】:

      我认为Counter 类对你有用。

      from collections import Counter
      array = [1, 0, 0, 0, 1]
      counter = Counter(array)
      mc = counter.most_common(20)
      print(mc)
      
      # [(0, 3), (1, 2)]
      most_common = mc[0][0] #  = 0
      number_same = mc[0][1] #  = 3
      positions = [i for i, x in enumerate(array) if x == most_common]
      

      最后一行来自这个SO post

      【讨论】:

      • 感谢您的建议,但是如果您随后给出一个没有连续序列的数组,它仍然给出不正确的输出...
      【解决方案4】:

      这不是一个完整的答案,但它是一个开始。

      这使用与itertools 库关联的groupby() 方法。 groupby() 方法查找连续的值组(而不是真正的值组),因此它非常适合查找序列。

      array = [1, 0, 0, 0, 1]
      
      from itertools import groupby
      
      g = groupby(array)
      for value, grp in g:
      

      grp 是一个迭代器...我们可以通过使用list() 函数对其进行强制转换来公开内容,从而将值提取到一个列表中。

          grp = list(grp)
          length = len(grp)
      

      使用inif 语句是检查各种值的便捷方法。

          if length in [3, 4, 5]:
              print('number_same =', length)
              print('element =', value)
              print('positions =', 'still working on this')
      
      ==== OUTPUT ====
      number_same = 3
      element = 0
      positions = still working on this
      

      【讨论】:

      • 谢谢!到目前为止,似乎对有和没有连续序列的两个数组都有效。 :-) 如果您为这些职位提供任何帮助,我将非常感激 ;-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 2016-01-13
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多