answer = ''
strL = [str(num) for num in numbers]
strl = list(map(str,numbers))
strL.sort(key=lambda num: num*3, reverse=True)
strL.sort(key=lambda num: (num*4)[:4], reverse=True)
answer = str(''.join(i for i in strL))
# l = ['3','30','341','4','34']
# l2 = ['333','303030','341341341','444','343434','31']
# l.sort()
# l2.sort()
# print(l2)
return answer
3을 곱하는 이유는 2번째 예시를 풀 때 이유를 알게 된다.
계산할 때 사전값으로만 정렬을 한다면 [9,5,34,30,3] 이렇게 정렬된다.
하지만 3이 30보다 앞에 와야한다.
number는 1000이하의 숫자이므로 최대값을 생각해 3을 곱해줬고,
==> 1000보다 작기때문에 문자를 동일하게 3번 붙여서 문자 기준으로 정렬을 했다. 그래서 아래처럼 비교를 하면
3을 곱하게 되면 [999, 555, 343434, 303030, 333] 이렇게 될 것이고, 정렬을 하게 되면 [999, 555, 343434, 333, 303030]이 된다.
>>> sorted([3, 5, 2, 1, 4])
[1, 2, 3, 4, 5]
>>> sorted(["D", "A", "C", "B", "E"])
['A', 'B', 'C', 'D', 'E']
>>> nums = [3, 5, 2, 1, 4]
>>> sorted_nums = sorted(nums)
>>> print(nums)
[3, 5, 2, 1, 4]
>>> print(sorted_nums)
[1, 2, 3, 4, 5]
>>> sorted((3, 5, 2, 1, 4))
[1, 2, 3, 4, 5]
>>> sorted({3, 5, 2, 1, 4})
[1, 2, 3, 4, 5]
>>> sorted("35214")
['1', '2', '3', '4', '5']
정렬이후 리스트를 문자열로 만드려면 join() 이용.
+a
>>> ''.join(sorted("35214"))
'12345'
>>> sorted(["2", 1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
>>> nums = [3, 5, 2, None, 1, 4]
>>> sorted(nums)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'NoneType' and 'int'
>>> sorted([num for num in nums if num])
[1, 2, 3, 4, 5]
>>> countries = [
{'code': 'KR', 'name': 'Korea'},
{'code': 'CA', 'name': 'Canada'},
{'code': 'US', 'name': 'United States'},
{'code': 'GB', 'name': 'United Kingdom'},
{'code': 'CN', 'name': 'China'}
]
>>> sorted(countries)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'
예를 들어, 국가 코드를 기준으로 정렬하면 코드를 기준으로 영국(GB)이 한국(KR) 앞에 오게 된다.
>>> sorted(countries, key=lambda country: country["code"])
[
{'code': 'CA', 'name': 'Canada'},
{'code': 'CN', 'name': 'China'},
{'code': 'GB', 'name': 'United Kingdom'},
{'code': 'KR', 'name': 'Korea'},
{'code': 'US', 'name': 'United States'}
]
국가 이름을 기준으로 정렬을 해보면,
이 기준으로는 한국(Korea)이 영국(United Kingdom)보다 앞에 오는 것을 볼 수 있다.
sorted(countries, key=lambda country: country["name"])
[
{'code': 'CA', 'name': 'Canada'},
{'code': 'CN', 'name': 'China'},
{'code': 'KR', 'name': 'Korea'},
{'code': 'GB', 'name': 'United Kingdom'},
{'code': 'US', 'name': 'United States'}
]
key 옵션은 서로 다른 자료형의 데이터를 정렬할 때도 활용할 수 있다.
위에서 숫자와 문자가 들어있는 배열과 함께 sorted() 함수를 호출했을 때 < 연산자가 지원되지 않아서 오류를 해결할 수 있다.
하지만 key 옵션에 int 함수를 넘기면 모든 데이터가 숫자로 취급되어 비교되기 때문에 정렬이 가능해질 것이다.
>>> sorted(["2", 1], key=int)
[1, '2']
이러한 차이점을 제외하고는 sort() 함수를 호출할 때도 reverse와 key 옵션을 동일한 방법으로 사용할 수 있다.
예를 들어, 양수와 음수가 섞여 있는 리스트를 절대값 기준으로 내림차순 정렬하면
>>> nums = [-3, 5, -2, -1, 4]
>>> nums.sort(reverse=True, key=abs)
>>> print(nums)
[5, 4, -3, -2, -1]