Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How append filtered string to new list in Python?

Tags:

python

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']
like image 724
Teerapat Avatar asked Nov 23 '25 02:11

Teerapat


2 Answers

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']
like image 88
trotta Avatar answered Nov 25 '25 15:11

trotta


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]
like image 41
Deadpool Avatar answered Nov 25 '25 16:11

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!