Python 연습 19:고급 목록 정렬
의문
예시
advanced_sort([1,2,1,2]) -> [[1,1],[2,2]]
advanced_sort([2,1,2,1]) -> [[2,2],[1,1]]
advanced_sort([3,2,1,3,2,1]) -> [[3,3],[2,2],[1,1]]
advanced_sort([5,5,4,3,4,4]) -> [[5,5],[4,4,4],[3]]
advanced_sort([80,80,4,60,60,3])-> [[80,80],[4],[60,60],[3]]
advanced_sort(['c','c','b','c','b',1,1])-> [['c','c','c'],['b','b'],[1,1]]
advanced_sort([1234, 1235, 1234, 1235, 1236, 1235])-> [[1234, 1234],[1235, 1235, 1235],[1236]]
advanced_sort(['1234', '1235', '1234', '1235', '1236', '1235'])-> [['1234', '1234'],['1235', '1235', '1235'],['1236']]
내 솔루션
>>separate the original list to different sublist
initialist a empty list: new_list
add the first number of orginal list into new_list
for each number in the original list:
if number equals to the first element of any sublist:
add number to that sublist
else:
add number to an new empty sublist
def advanced_sort(original_list: list) -> list:
# create a list with the first element of the original_list
new_list = [[original_list[0]]]
for index, item in enumerate(original_list):
if index == 0:
continue
not_added = True
# To iterate over every sublist in the new_list
for sublist_index, sublist in enumerate(new_list):
# try:
# if item is the same with first element of the sublist of new list and not already added
if item == sublist[0] and not_added:
# add item to that sublist
sublist.append(item)
not_added = False
# if no same item appear after checking the whole new list and not already added
if item != sublist[0] and sublist_index == len(new_list) - 1 and not_added:
# add the item the end of the new_list
new_list.append([item])
not_added = False
return new_list
기타 솔루션
def advanced_sort(lst):
return [[i] * lst.count(i) for i in sorted(set(lst), key=lst.index)]
>>transform the original list into a set, thus only unique item will appear
>>rearrange the transformed set by the index order
>>count how many time each unique appear in the original list
>>form a new list by putting in each item times their occurance in a sublist
내 반성
while
루프신용 거래
Reference
이 문제에 관하여(Python 연습 19:고급 목록 정렬), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mathewchan/python-exercise-19advanced-list-sort-2m1n텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)