我一直在尝试创建一个可以采用任意大小的两个列表(例如,列表A和列表B)的函数,并查看列表B是否出现在列表A中,但是连续且按相同顺序。如果以上为真,则返回True,否则返回False
EG
A:[9,0,**1,2,3,4,5,6,**7,8] and B:[1,2,3,4,5,6] is successful
A:[1,2,0,3,4,0,5,6,0] and B:[1,2,3,4,5,6] is unsuccessful.
A:[1,2,3,4,5,6] and B [6,5,3,2,1,4] fails because despite having the same
numbers, they aren't in the same order
到目前为止,我已经尝试使用嵌套循环这样做,并且对于去哪里感到有点困惑
试试这个:
L1 = [9,0,1,2,3,4,5,6,7,8]
L2 = [1,2,3,4,5,6]
c = 0
w = 0
for a in range(len(L2)):
for b in range(w+1, len(L1)):
if L2[a] == L1[b]:
c = c+1
w = b
break
else:
c = 0
if c == len(L2):
print('yes')
break
在这里,检查l2的元素是否在l1中,如果是这样,则断开第一个循环,记住你离开的位置和l2的下一个元素与l1的下一个元素相同,依此类推。
最后一部分是检查这是否发生的次数与l2的长度相同。如果是这样,那么你知道声明是正确的!
如果您的数组不是很大,并且您可以找到一种方法将数组中的每个元素映射到字符串,您可以使用:
list1 = [9,0,1,2,3,4,5,6,7,8]
list2 = [1,2,3,4,5,6]
if ''.join(str(e) for e in list2) in ''.join(str(e) for e in list1):
print 'true'
它只是从列表中创建两个字符串,而不是使用“in”来查找任何一个性能
试试这个:
L1 = [9,2,1,2,0,4,5,6,7,8]
L2 = [1,2,3,4,5,6]
def sameorder(L1,L2):
for i in range(len(L1)-len(L2)+1):
if L1[i:len(L2)+i]==L2:
return True
return False
您可以创建可以分析的a
子列表:
def is_consecutive(a, b):
return any(all(c == d for c, d in zip(b, i)) for i in [a[e:e+len(b)] for e in range(len(a)-len(b))])
cases = [[[9, 0, 1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6]], [[1, 2, 0, 3, 4, 0, 5, 6, 0], [1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6], [6, 5, 3, 2, 1, 4]]]
final_cases = {"case_{}".format(i):is_consecutive(*a) for i, a in enumerate(cases, start=1)}
输出:
{'case_3': False, 'case_2': False, 'case_1': True}