Home > Blockchain >  Python - Filter items in two lists matching given pattern
Python - Filter items in two lists matching given pattern

Time:12-21

Having the 3 lists in my Python code:

ListIterationData = ["01-2021", "02-2021"]

ListOne = ["FileName1-01-2021", "FileName1-02-2021", "FileName1-03-2021", "FileName1-04-2021"]

ListTwo = ["Filename2-01-2021", "Filename2-05-2021"]

Use case: As a user, I want to loop through items in "ListIterationData" and find matching items in both "ListOne" and "ListTwo" that ends with ListIterationData[i]. Items in "ListIterationData" would function as matching patterns in "ListOne" and "ListTwo". Something like:

ListOne_Filtered = []
ListTwo_Filtered = []

For item in ListIteration Data:
if item in ListOne endswith ListIterationData[i] AND item in ListTwo endswith ListIterationData[i]

Then append both ListOne_Filtered and ListOne_Filtered

The following would be my expected results:

ListOne_Filtered = ["FileName1-01-2021"]
ListTwo_Filtered = ["Filename2-01-2021"]

Many thanks for your help

CodePudding user response:

You could solve this with regex:

ListIterationData = ["01-2021", "02-2021"]
ListOne = ["FileName1-01-2021", "FileName1-02-2021", "FileName1-03-2021", "FileName1-04-2021"]
ListTwo = ["Filename2-01-2021", "Filename2-05-2021"]

list_one_filtered = []
list_two_filtered = []

for item in ListIterationData:
    for file_one, file_two in zip(ListOne, ListTwo):
        if re.search(item   "$", file_one) and re.search(item   "$", file_two):
            list_one_filtered.append(file_one)
            list_two_filtered.append(file_two)

print(list_one_filtered) # ['FileName1-01-2021']
print(list_two_filtered) # ['Filename2-01-2021']

So iterating through your iteration data, and iterating through both list one and list two concurrently, and then checking whether regex that both files end with the desired ending using the "$" symbol as an anchor.

CodePudding user response:

Try this:

ListOne_Filtered, ListTwo_Filtered = [], []
for i in range(min(len(ListIterationData), len(ListOne), len(ListTwo))):
    if ListOne[i].endswith(ListIterationData[i]) and ListTwo[i].endswith(ListIterationData[i]):
        ListOne_Filtered.append(ListOne[i])
        ListTwo_Filtered.append(ListTwo[i])
  • Related