-2

I have a list which consists of alphabets and spaces:

s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j'];

I need to split it into smaller individual lists:

s=[['a','b'],['b','c'],['d','e','f','g','h'],['i','j']]

I am new to python.

The entire code:

#To get the longest alphabetical substring from a given string

s = input("Enter any string: ")
alpha_string = []

for i in range(len(s)-1): #if length is 5: 0,1,2,3

if(s[i] <= s[i+1]):
    if i == len(s)-2:
        alpha_string.append(s[i])
        alpha_string.append(s[i+1])
    else:
        alpha_string.append(s[i])

if(s[i] > s[i+1] and s[i-1] <= s[i]):
    alpha_string.append(s[i])
    alpha_string.append(" ")

if(s[i] > s[i+1] and s[i-1] > s[i]):
    alpha_string.append(" ")

print(alpha_string)

#Getting the position of each space in the list
position = []
for j in range(len(alpha_string)):
if alpha_string[j] == " ":
    position.append([j])

print(position)        

#Using the position of each space to create slices into the list
start = 0
final_string = []
for k in range(len(position)):
    final_string.append(alpha_string[start:position[k]])
    temp = position[k]
    start = temp

print(final_string)`
James Z
  • 12,209
  • 10
  • 24
  • 44
hpx2331
  • 3
  • 4
  • 4
    Being new to StackOverflow and/or programming does not imply you can drop problems without any effort from your side. At least show an attempt, then we can help you with problems in the attempt. – Willem Van Onsem Apr 10 '18 at 10:04
  • 1
    Possible duplicate of [Make Python Sublists from a list using a Separator](https://stackoverflow.com/questions/6164313/make-python-sublists-from-a-list-using-a-separator) – Aran-Fey Apr 10 '18 at 10:25
  • Sorry for not showing the effort-part. – hpx2331 Apr 10 '18 at 10:35

5 Answers5

1

Try a list comprehension as follows

print([list(i) for i in ''.join(s).split(' ') if i != ''])

[['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]

JahKnows
  • 2,618
  • 3
  • 22
  • 37
  • This only works for single-character strings though. We don't know if the OP's real data is really all single characters. – Aran-Fey Apr 10 '18 at 10:07
  • 4
    Nor do we know if the OP has put any effort into solving the problem him/herself. – Willem Van Onsem Apr 10 '18 at 10:08
  • @WillemVanOnsem and Aran-Fey, True. Hopefully, he can take this and ask himself what is a list comprehension and down the rabbit hole he goes. – JahKnows Apr 10 '18 at 10:09
  • @JahKnows: my experience is that this will be copy-pasted. I once answered a question with some complex dynamic programming approach. Two days later another question appeared on SO with exactly the answer I gave from a team member that wanted to understand what that algorithm did. – Willem Van Onsem Apr 10 '18 at 10:10
  • @WillemVanOnsem, I see. – JahKnows Apr 10 '18 at 10:13
1

Here generator will be perfect :

s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j'];

def generator_approach(list_):
    list_s=[]
    for i in list_:
        if i==' ':
            if list_s:
                yield list_s
            list_s=[]
        else:
            list_s.append(i)

    yield list_s

closure=generator_approach(s)
print(list(closure))

output:

[['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
1

Or simply in one line, result = [list(item) for item in ''.join(s).split()]

Oli
  • 1,313
  • 14
  • 31
0

This is one functional way.

s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j']

res = list(map(list, ''.join(s).split()))

# [['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]
jpp
  • 159,742
  • 34
  • 281
  • 339
0
from itertools import groupby

s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j']

t = [list(g) for k, g in groupby(s, str.isspace) if not k]

print(t)

OUTPUT

[['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]

This doesn't require the strings to be single letter like many of the join() and split() solutions:

>>> from itertools import groupby
>>> 
>>> s = ['abc','bcd',' ',' ','bcd','cde',' ','def','efg','fgh','ghi','hij',' ','ijk','jkl']
>>> 
>>> [list(g) for k, g in groupby(s, str.isspace) if not k]
[['abc', 'bcd'], ['bcd', 'cde'], ['def', 'efg', 'fgh', 'ghi', 'hij'], ['ijk', 'jkl']]
>>> 

I can never pass up an opportunity to (ab)use groupby()

cdlane
  • 40,441
  • 5
  • 32
  • 81