I would like to append a string to new list that filtered from old list.
What I've tried so far:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = []
japanese = []
def filter_str(lang):
if 'tha' in lang:
return True
else:
return False
filter_lang = filter(filter_str, languages)
thai = thai.append(filter_lang)
print(thai)
My expected output is:
['thai01', 'thai02', 'thai03']
You could use a list comprehension:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = [x for x in languages if 'thai' in x]
print(thai)
Outputs:
['thai01', 'thai02', 'thai03']
To help you understand the logic of this oneliner, see the following example based on your code:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = []
def filter_str(lang):
if 'tha' in lang:
return True
else:
return False
for x in languages:
if filter_str(x):
thai.append(x)
print(thai)
# ['thai01', 'thai02', 'thai03']
The for loop that checks whether the string 'tha' occurs (in this example with the help of your function), is the same logic as the list comprehension above (although with the first example you wouldn't even need the function). You could also use a list comprehension in combination with your function:
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
def filter_str(lang):
if 'tha' in lang:
return True
else:
return False
thai = [x for x in languages if filter_str(x)]
print(thai)
# ['thai01', 'thai02', 'thai03']
You can also use filter with lambda function
languages = ['thai01', 'thai02', 'thai03', 'jap01', 'jap02', 'jap03']
thai = list(filter(filter_str,languages)) # or thai = list(filter(lambda x:'thai' in x,languages))
print(thai) #['thai01', 'thai02', 'thai03']
or list comprehension
thai = [y for y in languages if 'tha' in y]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With