How to extract multiple strings from list spaced apart

Question:

I have the following list:

lst = ['L38A', '38', 'L', 'A', '-6.7742', '-3.5671', '0.00226028', '0.4888', 'L38C', '38', 'L', 'C', '-7.7904', '-6.6306', '0.0', '0.4888', 'L38D', '38', 'L', 'D', '-6.3475', '-3.0068', '0.00398551', '0.4888', 'L38E', '38', 'L', 'E', '-6.4752', '-3.4645', '0.00250913', '0.4888']

I’m looking to extract the first element (posiiton 0) in the list (‘L38A’) and the 5th element (position 4) (-6.7742) multiple times:

Desired output
[('L38A','-6.7742'), ('L38C','-7.7904'), ('L38D','-6.3475')...('L38E','-6.4752')]

I have tried:
lst[::5]

Asked By: Chip

||

Answers:

This works:

a=[(x,y) for x,y in zip(*[iter(lst[::4])]*2)]

print(a)

# [('L38A', '-6.7742'), ('L38C', '-7.7904'), ('L38D', '-6.3475'), ('L38E', '-6.4752')]
Answered By: Swifty

We can handle this via a zip operation and list comprehension:

lst = ['L38A', '38', 'L', 'A', '-6.7742', '-3.5671', '0.00226028', '0.4888', 'L38C', '38', 'L', 'C', '-7.7904', '-6.6306', '0.0', '0.4888', 'L38D', '38', 'L', 'D', '-6.3475', '-3.0068', '0.00398551', '0.4888', 'L38E', '38', 'L', 'E', '-6.4752', '-3.4645', '0.00250913', '0.4888']
it = [iter(lst)] * 8
output = [(x[0], x[4]) for x in zip(*it)]
print(output)

This prints:

[('L38A', '-6.7742'), ('L38C', '-7.7904'), ('L38D', '-6.3475'), ('L38E', '-6.4752')]

The first zip generates a list of 8 tuples, with 8 being the number of values in each cycle. The comprehension then generates a list of 2-tuples containing the first and fifth elements.

Answered By: Tim Biegeleisen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.