begin.py
begin.py

Reputation: 161

Iterating between 2 lists

I have 2 lists: 1 of which is a lists of lists. They are as follows-

lists_of_lists = ['1', '4', '7', '13', '16', '21', '32', '36'],['3', '6', '8', '14', '22', '26', '31', '40']

just_a_list =['THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG', 'IWOULDLOVETOGETOVERWITHTHISASSOONASPOSSIBLE']

The lists_of_lists are used for slicing the elements of just_a_list such that: ['1', '4', '7', '13', '16', '21', '32', '36'] would slice the string 'THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG' as follows

'1' - '4' - 'HEQU'
'7' - '13' - 'KBROWNF'
'16' - '21' - 'JUMPED'
'32' - '36' - 'ZYDOG'

points to note-

Each list in list_of_lists will have an even number of numbers.

The list at i'th position in list_of_lists will belong to the string present at the i'th position in just_a_list.

Please help me out as to how do I carry out the process described above..

Thanks

Upvotes: 0

Views: 117

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

Use zip() to combine the string and slice lists, then use a zip() plus iter() trick to pair the start and stop values:

for slicelist, text in zip(lists_of_lists, just_a_list):
    for start, stop in zip(*([iter(slicelist)]*2)):
        print(text[int(start):int(stop) + 1])

Note that we have to add 1 to the stop index, as your appear to need it to be inclusive, while in Python the stop index is exclusive.

This gives:

>>> for slicelist, text in zip(lists_of_lists, just_a_list):
...     for start, stop in zip(*([iter(slicelist)]*2)):
...         print(text[int(start):int(stop) + 1])
... 
HEQU
KBROWNF
JUMPED
YDOG
ULDL
VETOGET
HTHIS
ONASPOSSIB

Upvotes: 5

ninMonkey
ninMonkey

Reputation: 7511

If I understand you right:

>>> ls = just_a_list =['THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG', 'IWOULDLOVETOGETOVERWITHTHISASSOONASPOSSIBLE']

>>> ls[0]
'THEQUICKBROWNFOXJUMPEDOVERTHELAZYDOG'

# so we do    
# your index was off by one
>>> ls[0][1:5]
'HEQU'

>>> ls[0][7:14]
'KBROWNF'

Upvotes: 0

Related Questions