Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension with duplicated function call [duplicate]

I want to transform a string such as following:

'   1   ,   2  ,    ,   ,   3   '

into a list of non-empty elements:

['1', '2', '3']

My solution is this list comprehension:

print [el.strip() for el in mystring.split(",") if el.strip()]

Just wonder, is there a nice, pythonic way to write this comprehension without calling el.strip() twice?

like image 248
peter.slizik Avatar asked Oct 31 '17 10:10

peter.slizik


People also ask

How do you remove duplicates from list comprehension?

To remove duplicates from a list in Python, iterate through the elements of the list and store the first occurrence of an element in a temporary list while ignoring any other occurrences of that element. The basic approach is implemented in the naive method by: Using a For-loop to traverse the list.

Can you have duplicate values in a list?

What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.


2 Answers

You can use a generator inside the list comprehension:

  [x for x in (el.strip() for el in mylist.split(",")) if x]
#             \__________________ ___________________/
#                                v
#                        internal generator

The generator thus will provide stripped elements, and we iterate over the generator, and only check the truthiness. We thus save on el.strip() calls.

You can also use map(..) for this (making it more functional):

  [x for x in map(str.strip, mylist.split(",")) if x]
#             \______________ ________________/
#                            v
#                           map

But this is basically the same (although the logic of the generator is - in my opinion - better encapsulated).

like image 86
Willem Van Onsem Avatar answered Sep 30 '22 23:09

Willem Van Onsem


As a simple alternative to get a list of non-empty elements (in addition to previous good answers):

import re

s = '   1   ,   2  ,    ,   ,   3   '
print(re.findall(r'[^\s,]+', s))

The output:

['1', '2', '3']
like image 35
RomanPerekhrest Avatar answered Sep 30 '22 23:09

RomanPerekhrest