Reputation: 63
I'm trying to remove items within list1 of the same index based on the occurence of a substring in list2.
List1 = ["1", "2", "3", "4"]
List2 = ["Remove1", "Remove2", "OtherValue1", "Othervalue2"]
Result should be:
List1 = ["3", "4"]
List2 = ["OtherValue1", "Othervalue2"]
From a logical view:
Check if element in List2 starts with/includes substring "Remove" and if true: remove this entry and entry in List1 with the same index.
I searched a lot of threads & questions but usually they want to compare 2 lists with (partially) identical entries and filter them accordingly. There are numerous ways I could think of performing it from a logical point of view, unfortunately I'm lacking of pythons syntax knowledge to put it together (once I would see the correct code I most likely will say "sure, easy, makes sense" -.-")
Thanks for the help in advance, Toby
Upvotes: 1
Views: 303
Reputation: 73
You can try this
def RemoveItems(List1, List2):
List1 = ["1", "2", "3", "4"]
List2 = ["Remove1", "Remove2", "OtherValue1", "Othervalue2"]
index = []
for item in List2:
if item.startswith('Remove'):
index.append(List2.index(item))
index.reverse()
for item in index:
del List1[item]
del List2[item]
return (List1, List2)
List1, List2 = RemoveItems(List1, List2)
print("List1 : ", List1)
print("List2 : ", List2)
Upvotes: 0
Reputation: 83
Assuming the conditions remain same. Applying the same logic for better understanding.Simply assign the remaining elements to the same list(here assuming that Remove string comes before OtherValue in these lists).
list1 = ["1", "2", "3", "4"]
list2 = ["Remove1", "Remove2", "OtherValue1", "Othervalue2"]
for i,j in zip(list1, list2):
if "Remove" in j:
list1 = list1[1:]
list2 = list2[1:]
print(list1)
print(list2)
Upvotes: 0
Reputation: 416
You can use zip() to zip the two lists into a list of tuples and then iterate through it.
>>> List1 = ["1", "2", "3", "4"]
>>> List2 = ["Remove1", "Remove2", "OtherValue1", "Othervalue2"]
>>> result1 = []
>>> result2 = []
>>> for x,y in zip(List1,List2):
... if "Remove" not in y:
... result1.append(x)
... result2.append(y)
>>> result1
['3', '4']
>>> result2
["OtherValue1", "Othervalue2"]
Upvotes: 2