Python 2.4.x
I have a series of lines that I’m reading in – rearranging and then making each line into a list which is nested inside another list.
I’ve got the following.
testposition = (22, 3, 1, 2, 18, 19, 5, 6, 8, 9, 12, 23, 24, 25, 26, 27, 28)
def giveme(s, words=()):
lista = s.split()
return [lista[item-1] for item in words]
for rec in testline:
testlist.append(giveme(rec, testposition))
In other words – if the rec being passed is.
Lorem ipsum dolor sit amet consectetur adipiscing elit In vitae neque nec magna tristique ornare Cras faucibus risus eu odio pharetra interdum Nunc dui mi rhoncus ut aliquet
then the list for this line would be. (after rearranging). (this list would get appended to another list – nested lists).
['interdum', 'dolar', 'Lorem', 'ipsum', 'risus', 'eu', 'amet', 'consectetur', 'elit', 'In', 'nec', 'Nunc', 'dui', 'mi', 'rhoncus', 'ut', 'aliquet']
Which it does fantastically well. However what I’d like to do is take the last 6 and group them together like this.
['interdum', 'dolar', 'Lorem', 'ipsum', 'risus', 'eu', 'amet', 'consectetur', 'elit', 'In', 'nec', 'Nunc dui mi rhoncus ut aliquet']
And if the line being passed does not have 28 elements but say only 25 – than it just groups whatever beyond the 22nd element – (the text is not the same line after line).
i.e the above example has 28 elements, this one has 25.
Lorem ipsum dolor sit amet consectetur adipiscing elit In vitae neque nec magna tristique ornare Cras faucibus risus eu odio pharetra interdum Nunc dui mi
and the resulting list would be:
['interdum', 'dolar', 'Lorem', 'ipsum', 'risus', 'eu', 'amet', 'consectetur', 'elit', 'In', 'nec', 'Nunc dui mi']
Hope that’s clear – any ideas?
Thank you.
If you supply the optional second argument to str.split, you can control how many splits are performed:
yields
while
yields