Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

python - Splitting a list into single list amounts

I'm trying to split a list in python to single amounts but I can't seem to get it to work and I can't find any questions on stackoverflow which try to achieve this

At the moment, I've got code which is producing id's but I need those id's separate

['325', '323', '324', '322']

I want to split these so they go into

['323']
['324']
['322']

What would be the best way to do this?

The list has different amounts and some of them only have one id

question from:https://stackoverflow.com/questions/65924521/splitting-a-list-into-single-list-amounts

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

since you want each element of the list in a separate/individual list, then you have to iterate through the original list and add an element in a empty list and append that new list to the resultant list.

 main_list = ['325', '323', '324', '322']
 final_solution = []
 for element in main_list:
       tmp = [element]
       final_solution.append(tmp)
 print(final_solution)

 # output -> [['325'], ['323'], ['324'], ['322']]`

or, by using list comprehension

final_solution = [[element] for element in main_list]
print(final_solution)

# output -> [['325'], ['323'], ['324'], ['322']]`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...