How to create lists in list where every future list is separate by spaces in list

Viewed 162

User provides input with spaces:

row = list(input())

print(row)

['1','2','3',' ','4','5','6',' ','7','8','9',' ']

So I need to create 'row' list into the below. The list is divided into sub-lists based on whitespace:

[['1','2','3'],['4','5','6'],['7','8','9']]
4 Answers

You can use str.split to split by whitespace:

myinput = '123 456 789'
row = list(map(list, myinput.split()))

print(row)

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Alternatively, using a list comprehension:

row = [list(i) for i in myinput.split()]

You can usestr.split to split the input on spaces to give a list of sub-strings.

E.g. '123 456 789' would become ['123', '456', '789'].

Then use a list-comprehension to convert these strings into lists of characters with the list() constructor (as you are already familiar with).

Making the final code:

row = [list(s) for s in input().split()]
#[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Starting with your list rather than the string, you can do that using itetools.groupby:

from itertools import groupby

row = ['1','2','3',' ','4','5','6',' ','7','8','9',' ']

out = [list(group) for key, group in groupby(row, lambda x: x != ' ') if key]
print(out)
# [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

We group the values depending on whether or not they are spaces, and only keep the groups that are not made of spaces.

Try this:

abc=['1','2','3',' ','4','5','6',' ','7','8','9',' ']
newList=list()
temp=list()
for i in abc:
    if(i==' '):
      newList.append(temp)
      temp=list()
    else:
      temp.append(i)
print(newList)

Output:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Related