python - 存储在列表中的特定序列

标签 python list python-3.x return

我正在寻找一种有效搜索具有特定值序列的列表的方法。顺序很重要!例如:

[x,y,z] 和 [x,z,y] 包含相同的值,但它们的顺序不同

但是:

  • [x,y,z]、[y,z,x] 和 [z,x,y] 对我来说都是一样的。
  • [x,z,y]、[z,y,x] 和 [x,z,y] 也都是一样的。

我想运行一个脚本来查找部分连接。例如,如果我正在寻找 [x,y,z] 我会寻找

mylist1 = ['a','b','c']
mylist2 = ['b','a','c']
def is_sequence_same(thelist,somelist):
    if (thelist[0] == somelist[0] and thelist[1] == somelist[1]):
       return True
    if (thelist[1] == somelist[1] and thelist[2] == somelist[2]):
        return True
    if (thelist[0] == somelist[1] and thelist[1] == somelist[0]):
        return False
    if  (thelist[0] == somelist[2] and thelist[1] == somelist[2]):
        return False
    else:
        return None
is_sequence_same(mylist1,mylist2)

函数返回: 是的 - 如果序列与我要求的相同, False - 如果顺序相反

我当前的功能不完整。但是,我认为应该有更优雅的方法来解决这个问题

最佳答案

使用双端队列:

from collections import deque

def is_sequence_same(l1, l2):
    if l1 == l2:
        return True
    if set(l1) != set(l2) or len(l1) != len(l2):
        return False
    d2 = deque(l2)
    for i in range(len(l2)):
        if l1 == list(d2):
            return True
        d2.rotate()
    return False

关于python - 存储在列表中的特定序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24449482/

相关文章:

pandas - 如何按列表中的值对数据框进行排序

python 列主矩阵和行主矩阵

python - Keras LSTM 层实现背后的架构是什么?

python - 在 Ubuntu 16.04 上安装 Tensorflow

python - 从 sub dag 中拉取 xcom

C++:STL 链表 - += 复制节点

python - 矩阵列表理解均值

python - 使用 Python 3 删除 "characters with encodings larger than 3 bytes"

python - 为什么我的 python 列表是垂直的?

python - 没有名为包装的模块