如果两个字符串按特定顺序出现,则从列表中获取元素



假设我有以下列表

lst=[['AAAB'],['ACAC'],['CABA'],['AACC'],['BACB'],['BCAA'],['CBAA'],['ABBC']]

我需要提取出现A然后出现C的列表,而不考虑它们之间可能存在的其他字母。

因此,结果一定类似

res=[['ACAC'],['AACC'],['BACB'],['ABBC']]

我可以在另一个for循环中实现for循环,该循环进入每个列表,然后在每个字符串上迭代,看看A是否出现,C是否出现,但我对如何保持幻影的顺序有点困惑,即A出现在C之前

lst=[['AAAB'],['ACAC'],['CABA'],['AACC'],['BACB'],['BCAA'],['CBAA'],['ABBC']]
out = [[i] for (i, ) in lst if 'A' in i and 'C' in i and i.index('A') < i.index('C')]
print(out)

打印:

[['ACAC'], ['AACC'], ['BACB'], ['ABBC']]

或使用re:

import re
r = re.compile(r'A.*C')
lst=[['AAAB'],['ACAC'],['CABA'],['AACC'],['BACB'],['BCAA'],['CBAA'],['ABBC']]
out = [[i] for (i, ) in lst if r.search(i)]
print(out)

@OlvinRocht:的解决方案

lst=[['AAAB'],['ACAC'],['CABA'],['AACC'],['BACB'],['BCAA'],['CBAA'],['ABBC']]
res = [i for i in lst if len(i[0]) > i[0].find('C') - i[0].find('A') > 0]
print(res)

扩展@andrej-regex解决方案

import re
r = list(filter(lambda x: [i for i in x if re.findall('A.*C', i)], l))

非正则表达式,解决方案

def find_patt(lis):
res =[]
for sublis in lis:
tmp =[]
for ele in sublis:
if ('A' in ele) and ('C' in ele):
if ele.index('A')<len(ele)-ele[::-1].index('C'):
tmp.append(ele)
if tmp!=[]:
res.append(tmp)
tmp =[]
return res
lst=[['AAAB'],['ACAC'],['CABA'],['AACC'],['BACB'],['BCAA'],['CBAA'],['ABBC'], ['CAC']]
print(find_patt(lst))
# [['ACAC'], ['AACC'], ['BACB'], ['ABBC'], ['CAC']]

尝试以下操作:(编辑以说明不包含字符"A"或"C"的列表(

lst=[['AAAB'],['ACAC'],['CABA'],['AACC'],['BACB'],['BCAA'],['CBAA'],['ABBC']]
res = []
for lst_inner in lst:
if ('A' in lst_inner[0] and 'C' in lst_inner[0] and
lst_inner[0].find('A') < lst_inner[0].find('C')):

res.append(lst_inner)
print(res)
print("Hello world")
inputList=[['AAAB'],['ACAC'],['CABA'],['AACC'],['BACB'],['BCAA'],['CBAA'],['ABBC']]
print(inputList)
matchingCharactersInOrderList = ["A","C"]
filteredList=[]
for subList in inputList:
tempStringToMatchOrder=""
tempStringToMatchOrder = tempStringToMatchOrder.join(subList)
if  matchingCharactersInOrderList[0] in tempStringToMatchOrder:
partitionedString = tempStringToMatchOrder.partition(matchingCharactersInOrderList[0])[2]
if matchingCharactersInOrderList[1] in partitionedString:
filteredList.append(subList)
#matching = [s for s in lst if ("A" in s)]
print(filteredList)

尝试这个

lst =[['AAAB'],['ACAC'],['CABA'],['AACC'],['BACB'],['BCAA'],['CBAA'],['ABBC']]
res = []
def check(list_string):
index1=0
index2=0
for letters in list_string:
if letters == 'A':
index1 = list_string.index(letters)
break
for letters in list_string:
if letters =='C':
index2 = list_string.index(letters)
break
if index1 < index2:
return True
elif index1 > index2:
return False
else:
return False

for x in lst:
string = x[0]
string_splitted = list(string)
if check(string_splitted):
res.append(x)
print(res)

相关内容

  • 没有找到相关文章

最新更新