Home > database >  sorting list into list of lists based on number
sorting list into list of lists based on number

Time:07-16

So, I was wondering how to sort this list:

list = [
    '1',
    'China',
    'hello',
    '2',
    'India',
    '3',
    'America',
    'Texas',
    'Cowboy'
]

Into this new list of lists:

newlist = [
    ['1', 'China', 'hello'], 
    ['2', 'India'], 
    ['3', 'America', 'Texas', 'Cowboy']
]

So I got the solution for my own problem, which is this code:

list = [
    '1',
    'China',
    'hello',
    '2',
    'India',
    '3',
    'America',
    'Texas',
    'Cowboy'
]

newlist = []
a = 1
n = 0

for i in list:
    rltvList = list[n]
    
    if str(a) == rltvList:
        temporaryList = []
        a  = 1
        newlist.append(temporaryList)
        
    temporaryList.append(rltvList)
    n  = 1

Forgive my ugly coding, as I'm a beginner.

It's always good practice to write the pseudocode first before actually diving to the codes.

Here's my pseudocode logic for any of you wondering:

  1. Go through list / loop through list;
  2. If list[x] = '1' then append list[x] on to temporaryList;
  3. Keep appending on to temporaryList until list[x] = '2';
  4. Append temporaryList on to newList;
  5. Clear out temporaryList;
  6. Do it over and over again until end of list.

We need temporaryList because we need to make list of lists. Without temporaryList it'll just be a list.

CodePudding user response:

Done:

flat = ['1','China','hello','2','India','3','America','Texas','Cowboy']
target = []
n = 1
for i in flat:
    if i == str(n):
        target.append([i])
        n  = 1
    else:
        target[-1].append(i)

print(target)

Output:

[['1', 'China', 'hello'], ['2', 'India'], ['3', 'America', 'Texas', 'Cowboy']]

CodePudding user response:

Update to the existing code because if the list starts with for example '5000' it won't work and send out an error message. So we gonna do a try & except.

Here's the new code:

list= ['4000','this','text','will','be','skipped','1','China','hello','2','India','3','America','Texas','Cowboy']
newlist=[]
a=1
n=0

for i in list:
    rltvList= list[n]
    
    if str(a) == rltvList:
        temporaryList=[]
        a =1
        newlist.append(temporaryList)
    
    try:    
        temporaryList.append(rltvList)
    except Exception:
        pass
    
    n =1

print(newlist)

It will output:

newlist=[['1', 'China', 'hello'],['2', 'India'],['3', 'America', 'Texas', 'Cowboy']]

Sorry for the bad code, I'm a beginner. Feel free to share some simpler, more elegant code.

  • Related