2

i want to use a list comprehension to split elements of a list.

line = [x.split(", ") for x in lineList]

At same time I'd like to remove tailing and leading characters of the elements (.rstrip('"')/.lstrip('"').

But a 'list' object has no attribute 'rstrip'. Is there a way to achieve this within a comprehension or do i have to go for a for-loop?

Thanks in advance for any advice, Lars

LarsVegas
  • 6,522
  • 10
  • 43
  • 67
  • if you are trying to parse a json list then use `json.loads()` instead or if it is string list's `repr()` then use `ast.literal_eval()` instead. – jfs Oct 29 '16 at 15:33

3 Answers3

4

Try something like this :

line = [[y.rstrip('"') for y in x.split(", ")] for x in lineList]

with two list comprehensions inside.

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
3

If you want to remove both leading and trailing quotes, why not using strip() directly? Also, if you want to flatten the list of lists:

line = sum([[y.strip('"') for y in x.split(", ")] for x in lineList], [])
Chewie
  • 7,095
  • 5
  • 29
  • 36
  • Hi guys, thanks for your answers. Exactly what i was looking for but couldn't come up with. Cheers! – LarsVegas Dec 19 '11 at 14:04
  • @LarsVegas: [`sum(nested_list, [])` is an inefficient](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python#comment13288147_952946) and it is not the most readable way to [flatten a shallow list in Python](http://stackoverflow.com/q/952914/4279) – jfs Oct 29 '16 at 15:31
1

Personally, I find the nested list comprehension harder to read. Why not give this work to another function? Perhaps this deserves a better name, but:

def groom_line(l):
    return [elem.strip('"') for elem in l.split(",")]

and in your application,

return [groom_line(l) for l in linelist]
skatenerd
  • 60
  • 7