I have a couple of lists generator = ["one#zade", "one#zaat", "one#osde", "one#za"]
& accepted_channels = ["zade", "zaat"]
.
I am trying to extract elements from the generator
list which have as a substring any one of the values that are present in the accepted_channels
list.
I have a code and it works correctly, but it has 3 loops involved. Is there a way to write the code without any loops or with a reduced number of loops?
generator = ["one#zade", "one#zaat", "one#osde", "one#za"]
accepted_channels = ["zade", "zaat"]
final_records = []
for item in generator:
for channel in accepted_channels:
if channel in item:
final_records.append(item)
print(final_records) # prints ['one#zade', 'one#zaat']
P.S.: Here, the generator
only has 4 elements, but in real I have a list of more than 50000 elements.
CodePudding user response:
You should probably use filter()
generator = ["one#zade", "one#zaat", "one#osde", "one#za"]
accepted_channels = ["zade", "zaat"]
def check(s):
return any(y in s for y in accepted_channels)
print(list(filter(check, generator)))
Output:
['one#zade', 'one#zaat']
Performance check:
Built generator list with 50_000 elements each of 8 pseudo-random characters. Duration was 0.016s