我正在寻找一种有效搜索具有特定值序列的列表的方法。顺序很重要!例如:
[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/