Reputation: 47
I am trying to convert [CS-PP-GE-RI-ET]
which is the first element in a list to:
[CS]
[CS-PP]
[CS-PP-GE]
[CS-PP-GE-RI]
[CS-PP-GE-RI-ET]
Here is what I have got so far:
data = ['CS-PP-GE-RI-ET',
'CS-PP-ET-GE',
'CS-PP-ET-GE-BD',
'CS-PP-ET-GE',
'CS-PP-ET-CD-PI-GE']
word0 = []
word1 = []
for i in range(len(data)):
# print(i) # 0 1 2 3 4 ... however many elements are in data
split = data[i].split('-') # prints CS-PP-GE-RI-ET ...
# print(split) # this prints ['CS', 'PP', 'GE', 'RI', 'ET'] for each element
for j in range(len(split)-1): # you have to use range(len()-1 to iterate all the way to the end of the index count
# print(split[j]) # this prints each element CS PP GE RI ET CS PP ...
# word1.append(split[j])
temp0 = split[j]
word0.append(temp0)
temp1 = split[j + 1]
temp3 = temp0 + '-' + temp1
word0.append((temp3))
print(word0)
This is what I get though:
['CS', 'CS-PP', 'PP', 'PP-GE', 'GE', 'GE-RI', 'RI', 'RI-ET']
['CS', 'CS-PP', 'PP', 'PP-GE', 'GE', 'GE-RI', 'RI', 'RI-ET', 'CS', 'CS-PP', 'PP', 'PP-ET', 'ET', 'ET-GE']
...
I know I am missing a basic understanding of str
and append()
but can't seem to figure it out.
The final result should be:
[CS]
[CS-PP]
[CS-PP-GE]
[CS-PP-GE-RI]
[CS-PP-GE-RI-ET]
[CS]
[CS-PP]
[CS-PP-ET]
[CS-PP-ET-GE]
[CS]
...
Thanks for the help.
Upvotes: 3
Views: 69
Reputation: 1372
You can also do it like this:
for word in data:
for i in range(len(word)):
if word[i] == '-':
print([ word[:i] ])
print([ word ])
Or with list comprehension:
print( '\n'.join( str([ word[:i] ])
for word in data
for i in range(len(word))
if word[i] == '-' or i == len(word) - 1 ) )
Upvotes: 1
Reputation: 1112
This should write all your items into a list containing list, since your lists will need a place holder.
wrapper_list = list()
my_list = ['CS-PP-GE-RI-ET']
for str_item in my_list:
temp_string = ""
combined_string_list = list(str_item.split('-'))
for index in range(len(str_item)):
wrapper_list.append(["-".join(combined_string_list[0:index+1])])
print(wrapper_list)
Upvotes: 1
Reputation: 88226
We can use itertools.accumulate
here
from itertools import accumulate
l = 'CS-PP-GE-RI-ET'.split('-')
print(*accumulate(l, lambda x, y: '-'.join([x, y])), sep='\n')
CS
CS-PP
CS-PP-GE
CS-PP-GE-RI
CS-PP-GE-RI-ET
For a general solution you can do:
data = ['CS-PP-GE-RI-ET',
'CS-PP-ET-GE',
'CS-PP-ET-GE-BD',
'CS-PP-ET-GE',
'CS-PP-ET-CD-PI-GE']
def acc(s):
l = s.split('-')
func = lambda x, y: '-'.join([x, y])
return '\n'.join(accumulate(l, func))
print(*map(acc, data), sep='\n\n')
CS
CS-PP
CS-PP-GE
CS-PP-GE-RI
CS-PP-GE-RI-ET
CS
CS-PP
CS-PP-ET
CS-PP-ET-GE
CS
CS-PP
CS-PP-ET
CS-PP-ET-GE
CS-PP-ET-GE-BD
CS
CS-PP
CS-PP-ET
CS-PP-ET-GE
CS
CS-PP
CS-PP-ET
CS-PP-ET-CD
CS-PP-ET-CD-PI
CS-PP-ET-CD-PI-GE
Upvotes: 1