Reputation: 692
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.
Upvotes: 1
Views: 327
Reputation: 879083
If you supply the optional second argument to str.split, you can control how many splits are performed:
testposition = (22, 3, 1, 2, 18, 19, 5, 6, 8, 9, 12, 23)
def giveme(s, words=()):
lista = s.split(' ',22)
result=[lista[item-1] for item in words]
return result
rec='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'
print(giveme(rec, testposition)[-1])
yields
'Nunc dui mi rhoncus ut aliquet'
while
rec='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'
print(giveme(rec, testposition)[-1])
yields
'Nunc dui mi'
Upvotes: 3
Reputation: 39950
Assuming that on any line you only want to rearrange the first 22 words: You can use sequence slicing to select only the part you want to rearrange:
testposition = (22, 3, 1, 2, 18, 19, 5, 6, 8, 9, 12)
def giveme(s, words=()):
lista = s.split()
maxpos = max(testposition)
return [lista[item-1] for item in words[:maxpos]] + words[maxpos:]
for rec in testline:
testlist.append(giveme(rec, testposition))
Upvotes: 0