Home > Back-end >  Is there a way to convert specific subsequence of list to string?
Is there a way to convert specific subsequence of list to string?

Time:08-17

In the following piece of code I'm only printing out the sequence of elements in list that are increasing by 1

for example from this list

[88, 44, 4, 5, 6, 7, 18]

I want to print this

"4, 5, 6, 7" (converted to string)

I've managed to do the main part, but the output is [4, 5, 6, 7] instead of "4, 5, 6, 7"

 def __str__(self):
    for x, y in itertools.groupby(enumerate(self.lst), lambda z: z[0] - z[1]):
        elements = [i[1] for i in y]
        if len(elements) > 1:
            return str("".join(str(elements)))

​I hope this piece is enough. The entire code was just too big ​

CodePudding user response:

This fails because you convert the full list to string instead of the elements.

Use:

def __str__(self):
    for x, y in itertools.groupby(enumerate(self.lst), lambda z: z[0] - z[1]):
        elements = [i[1] for i in y]
        return ", ".join(map(str, elements))

Output: '4, 5, 6, 7'

Note that you could also use the below "hack" (convert the list to string, remove square brackets by slicing), but this doesn't allow you to customize the separator:

return str(elements)[1:-1]
  • Related