Leehbi
Leehbi

Reputation: 779

Combine list values in 1 string

I have list like this :

subsets = ["T10", "T12", "T13", "A15", "T23"]

I need to loop through this list checking for T followed by A and if this is found to merge T & A i.e.

This is the new list I need:

newset = ["T10", "T12", "T13, A15", "T23"]

I'm trying to figure out how to loop through the list and check for the left most value. I just need an expression for {left char of string of next list item} - I think!

for i in range(len(subsets)):
  if {left char of string for next list item} = "A":
    newset.append(subset[i]+", "+ subset[i+1])
    i+=1
  else:
    newset.append(subset[i]) 

Upvotes: 0

Views: 65

Answers (2)

gold_cy
gold_cy

Reputation: 14216

Here is a simple for loop approach that returns a new list:

f = []
for item in subsets:
    if f and (item[:1], f[-1][:1]) == ('A', 'T'):
        f[-1] = '{}, {}'.format(f[-1], item)
    else:
        f.append(item)

print(f)

['T10', 'T12', 'T13, A15', 'T23']

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121406

Build a new list from your items, and check if the last item in that list starts with T, and the current with A. If so, replace that last item in your new list:

it = iter(subsets)
result = [next(it)]
for elem in it:
    if elem[:1] == 'A' and result[-1][:1] == 'T':
        # preceding element is T.., this is A.., combine into a single string
        result[-1] = f'{result[-1]}, {elem}'
    else:
        result.append(elem)

I used iter() and next() to prime the output list with the first element efficiently, and save ourselves from having to test if result has at least one element.

Demo:

>>> subsets = ["T10", "T12", "T13", "A15", "T23"]
>>> it = iter(subsets)
>>> result = [next(it)]
>>> for elem in it:
...     if elem[:1] == 'A' and result[-1][:1] == 'T':
...         # preceding element is T.., this is A.., combine into a single string
...         result[-1] = f'{result[-1]}, {elem}'
...     else:
...         result.append(elem)
...
>>> result
['T10', 'T12', 'T13, A15', 'T23']

Note: this will also merge consecutive A* elements into a preceding T element, so [..., "T13", "A15", "A16", "T17", ...] results in [..., "T13, A15, A16", "T17", ...].

Upvotes: 3

Related Questions