1

I have a dataframe column, df['Traversal'], where each row may contain a string something like 'Paris->France->London'.

The correct output works for the following code:

emptylist = []
for x in df['Traversal']:
    for y in x.split('->'):
        emptylist.append(y)

I've tried variations of:

emptylist = [y.split('->') for y in df['Traversal']
emptylist = [y for y in x.split('->') for x in df['Traversal']]

The closest I got was a list of lists (split). The end result I would like is a list of all the strings only, not grouped by the 'split' lists.

hiimarksman
  • 261
  • 2
  • 3
  • 12

2 Answers2

0
[e for x in df["Traversal"] for e in x.split('->')]

Also see: Double Iteration in List Comprehension

Rocky Li
  • 5,641
  • 2
  • 17
  • 33
0

Why not:

emptylist = [y.split('->') for y in df['Traversal']
cities = []
_ = [cities.extend(t) for t in emptylist]

If you must use list-comprehensions ;)

rdas
  • 20,604
  • 6
  • 33
  • 46