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
temporaryList
untillist[x] = '2'
; - Append
temporaryList
on 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.
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.