Home > Enterprise >  python if/else statement with exception that keep elements if exist in another sub-list
python if/else statement with exception that keep elements if exist in another sub-list

Time:07-22

Let us say I have the following tokens in list :

['I', 'want', 'to', 'learn', 'coding', 'in', 'r', 'and', 'c  ', 'today', ',', 'and', 'then', 'I', "'ll", 'be', 'learning', 'c#', 'and', 'c']

I want to remove all tokens of length < 2 but want to keep elements of this sub-list:

['r','c','js','c#']

How can I do this in a single python list-comprehension ?

CodePudding user response:

You can use list comprehension with two conditions.

lst1 = ['I', 'want', 'to', 'learn', 'coding', 'in', 'r', 'and', 'c  ', 'today', ',', 'and', 'then', 'I', "'ll", 'be', 'learning', 'c#', 'and', 'c']

lst2 = ['r','c','js','c#']

res = [l for l in lst1 if (len(l)>=2) or (l in lst2)]
print(res)

['want',
 'to',
 'learn',
 'coding',
 'in',
 'r',
 'and',
 'c  ',
 'today',
 'and',
 'then',
 "'ll",
 'be',
 'learning',
 'c#',
 'and',
 'c']
  • Related