Home > Blockchain >  Is there a way to loop through a list in Python and check if a certain string is in every string ele
Is there a way to loop through a list in Python and check if a certain string is in every string ele

Time:01-22

I am trying to loop through a list and check each element of the list for a specific string pattern (some sort of nucleotide pattern for example and assuming all elements within the list are strings). How would one do this? I've attempted using the all() function in an if statement that was embedded in a for loop, but that didn't seem to work. Example of what I mean below:

 for i in range(0, len(list)):
    if thing in all(list):
        add thing to another list

CodePudding user response:

You could use a list comprehension to check each list element. Then sum that resulting list and assert that every string matched.

def allList(lst, elem):
    return len(lst) == sum([elem in x for x in lst])

inp = ["ATCGCGTTA", "CGCGATTA", "TTAGCGCA"]
print(allList(inp, "TTA"))  # True

CodePudding user response:

From "add thing to another list", I assume you want to add the strings that meet your search criteria to a new list. If so, then something along these lines should work:

candidates = ["dffcff", "ffceee", "fdddff", "ffeffd", "cefbaf", "ffeadf", "feeede", "effadf"]
pattern = "ffe"
selected = [
    s
    for s in candidates
    if pattern in s
]
print(selected)

Output:

['ffeffd', 'ffeadf']
  • Related