Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python 프로그램에서 요소의 길이에 따라 목록 정렬

<시간/>

문자열 목록이 있고 우리의 목표는 목록의 문자열 길이에 따라 목록을 정렬하는 것입니다. 문자열을 길이에 따라 오름차순으로 정렬해야 합니다. 알고리즘이나 Python을 사용하여 이 작업을 수행할 수 있습니다. 내장 메소드 sort() 또는 함수 sorted() 키와 함께.

출력을 보기 위해 예를 들어 보겠습니다.

Input:
strings = ["hafeez", "aslan", "honey", "appi"]
Output:
["appi", "aslan", "honey", "hafeez"]

sort(key) 및 sorted(key)를 사용하여 프로그램을 작성해 보겠습니다. sorted(key) 함수를 사용하여 원하는 출력을 얻으려면 아래 단계를 따르십시오.

알고리즘

1. Initialize the list of strings.
2. Sort the list by passing list and key to the sorted(list, key = len) function. We have to pass len as key for the sorted() function as we are sorting the list based on the length of the string. Store the resultant list in a variable.
3. Print the sorted list.

예시

## initializing the list of strings
strings = ["hafeez", "aslan", "honey", "appi"]
## using sorted(key) function along with the key len
sorted_list = list(sorted(strings, key = len))
## printing the strings after sorting
print(sorted_list)

출력

위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.

['appi', 'aslan', 'honey', 'hafeez']

알고리즘

1. Initialize the list of strings.
2. Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place. So, we don't need to store it in new variable.
3. Print the list.

예시

## initializing the list of strings
strings = ["hafeez", "aslan", "honey", "appi"]
## using sort(key) method to sort the list in place
strings.sort(key = len)
## printing the strings after sorting
print(strings)

출력

위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.

['appi', 'aslan', 'honey', 'hafeez']

결론

튜토리얼에 대해 궁금한 점이 있으면 댓글 섹션에 언급하세요.