HighAllegiant
HighAllegiant

Reputation: 71

Splitting a list into a pairs in Python

This is a homework. I'm not looking for answers, just a nudge into the right direction.

Given a list:

['The Boy','1:34','Let go','4:21','Wherever to', '5:30']

I want to be able to sort the list by pairs:

[['The Boy','1:34']['Let go','4:21']['Wherever to', '5:30']]

Upvotes: 2

Views: 3101

Answers (2)

John La Rooy
John La Rooy

Reputation: 304215

Difficult without knowing which parts of Python you have been taught so far, but here are some steps that may help

>>> ['The Boy','1:34','Let go','4:21','Wherever to', '5:30'][::2]
['The Boy', 'Let go', 'Wherever to']
>>> ['The Boy','1:34','Let go','4:21','Wherever to', '5:30'][1::2]
['1:34', '4:21', '5:30']
>>> zip(['The Boy', 'Let go', 'Wherever to'], ['1:34', '4:21', '5:30'])
[('The Boy', '1:34'), ('Let go', '4:21'), ('Wherever to', '5:30')]

You should use some variables instead of repeating the list over and over of course

Upvotes: 4

Raymond Hettinger
Raymond Hettinger

Reputation: 226366

  • Start with an empty list for the result
  • Loop over a variable i starting from zero, going to the length of the input, counting by twos
  • Extract the i-th value and the value at i+1
  • Put them in a tuple
  • Add the tuple to the result list
  • Repeat

Actual code left for homework ;-)

Upvotes: 2

Related Questions