2017-04-04 2 views
2

길이에 따라 목록에서 단어를 정렬하고 싶습니다. 나는에 실행 한길이 별 단어 목록 정렬 방법

{'balloon','jump','blue','balloon'} 

또 다른 문제는 파이썬의 종류는 우리가 사용하고 있다는 것입니다 :

테스트 케이스는이 방법을 통해 실행하면 {'cat','jump','blue','balloon'}

그것의 라인을 따라 뭔가를 인쇄 할 것이다 잘 작동하지만 파이썬 3.5.2 쉘에서 .py를 실행하려고하면 오류가 발생합니다.

나는 주로 내가 뭘 잘못했는지 알아야하며, 문제를 해결하기 위해 할 수있는 일을한다. 어떤 도움을 주셔서 감사합니다!

.py 파일은 파일

def wordSort(): 
    words = [] 
    minimum = 'NaN' 
    index = 0 
    x = 0  
    y = 0  
    z = 1 
    #How many words to be entered 
    length = input('How many words would you like to enter? ') 
    #Put words in the number of times you entered previously  
    while not z >= length + 1: 
     words.append(raw_input('Enter word #' + str(z) + ': ')) 
     z += 1 
    while x < length: 
     minimum = words[x] 
     #Goes through the list and finds a smaller word 
     while y < length: 
      if len(words[y]) < len(minimum): 
       minimum = words[y] 
       index = y 
      y += 1 
     words[index] = words[x] 
     words[x] = minimum 
     x += 1 
    print words 
+1

가능한 중복 것 [어떻게 객체의 속성에 기반하여 객체의 목록을 정렬하려면? ] (http://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) – congusbongus

+1

이것은 파이썬 2.x입니다. 아마도 2.7) 코드. 그것은 파이썬 2.x에서 실행되거나 파이썬 3에서 조정될 필요가 있습니다. –

답변

3
  • print 파이썬 3.5 함수이기 here:을 발견 print(words)로 사용되어야 할 수있다. 그것은 here
  • sorted를 사용하여 문자열의 길이에 따라 그들을 분류하는 데 사용할 수있는 단어,이 목록을 감안할에 대한 자세한 내용 :

    sorted(word_list , key = len)

+0

더 나은 :'sorted (word_list, key = len)' – hallazzang

+0

@hallazzang 예, 좋습니다. 코드에 추가되었습니다. –

0

이보십시오. 그것은 오름차순 내림차순를 들어

list_name.sort(key=len) 

문자열의 길이를 기준으로 목록을 정렬의

list_name.sort(key=len,reverse=True)