Home > Software design >  How to separate a list of characters into 2 separate lists but maintain their order in python
How to separate a list of characters into 2 separate lists but maintain their order in python

Time:06-08

This is what I have,

coordinates = ('S', 'W', 'W', 'S', 'E', 'S', 'E', 'N', 'N')

I would like to separate the list into 2 further lists (one containing the N and S values, the other containing the E and W values). However, the need to remain in the order they appear i.e.

new_coordinates_one = ('S', 'S', 'S', 'N', 'N')
new_coordinates_two = ('W', 'W', 'E', 'E')

CodePudding user response:

Use list comprehension with sets:

new_coordinates_one = [s for s in coordinates if s in {'N', 'S'}]
new_coordinates_two = [s for s in coordinates if s in {'E', 'W'}]

CodePudding user response:

new_coordinates_one = tuple(coor for coor in coordinates if coor == 'S' or coor == 'N')
new_coordinates_two = tuple(coor for coor in coordinates if coor == 'W' or coor == 'E')

Alternatively, to reduce the size of the code incase if the conditions to check are too many, we can use the in operator to check if it matches any of the elements in the set. Credits: @Marat

new_coordinates_one = tuple(coor for coor in coordinates if coor in ('N', 'S'))
new_coordinates_two = tuple(coor for coor in coordinates if coor in ('E', 'W'))

CodePudding user response:

Using list comprehension, as suggested by others, is a very Pythonic approach and is commendable.

However, one could argue that the iterable (coordinates) has to be parsed twice if that technique is used. Therefore, although the code isn't quite as neat, it can be done in one pass:

coordinates = ('S', 'W', 'W', 'S', 'E', 'S', 'E', 'N', 'N')

sn = []
ew = []

for c in coordinates:
    if c in 'SN':
        sn.append(c)
    else:
        ew.append(c) # assumption that if c is neither S nor N then it's either E or W


print(sn)
print(ew)
  • Related