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
  • 181
  • 1
  • 2
  • 11

2 Answers2

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

Also see: Double Iteration in List Comprehension

Rocky Li
  • 4,615
  • 1
  • 10
  • 24
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
  • 15,648
  • 5
  • 22
  • 36