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:
- Go through
list/ loop throughlist; - If
list[x] = '1'then appendlist[x]on totemporaryList; - Keep appending on to
temporaryListuntillist[x] = '2'; - Append
temporaryListon tonewList; - Clear out
temporaryList; - 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.