Gra*_*ley 3 python string list
我有一份清单
listOfStations = ['FSTL40503', 'LHSL40503', 'WEHL40503', 'BKGL40503', 'DDKL40503', 'RNML40503', 'PFLL40503', 'GRYL40503']
Run Code Online (Sandbox Code Playgroud)
我想先检查FSTL40503是否排在首位,然后PFLL40503排在第二位.我目前可以找到两者是否存在,但它不尊重我想要的顺序.
toBeChecked=['PFLL40503','FSTL40503']
if all(item in listOfStations for item in toBeChecked):
print "Both stations found in order, in list"
Run Code Online (Sandbox Code Playgroud)
这当前打印它不应该做,因为它不是正确的路线.
我还试图加入列表中的两个条目来制作字符串并检查,但我认为我很困惑需要做的事情:
z= ''.join(toBeChecked)
print z
for char in z:
if char not in listOfStations:
print listOfStations
continue
else:
listOfStations = listOfStations[listOfStations.index(char) + 1:]
confirmedTrainList.append(trainList[i])
Run Code Online (Sandbox Code Playgroud)
你可以得到一个迭代器,listOfStations
它会在搜索时使用列表,因此它永远不会考虑相同的元素两次.
def contains_in_order(container, items):
it = iter(container)
return all(item in it for item in items)
should_not_work = ['PFLL40503', 'FSTL40503']
should_work = ['FSTL40503', 'PFLL40503']
listOfStations = ['FSTL40503', 'LHSL40503', 'WEHL40503', 'BKGL40503', 'DDKL40503', 'RNML40503', 'PFLL40503', 'GRYL40503']
print(contains_in_order(listOfStations, should_not_work))
# False
print(contains_in_order(listOfStations, should_work))
# True
Run Code Online (Sandbox Code Playgroud)