과제를 위해 카드 게임을하고 있습니다. 이것이 마지막 부분입니다.
정렬해야합니다
Player 1 has won with 16 cards
Player 2 has won with 18 cards
Player 3 has won with 16 cards
Player 4 has won with 20 cards
Player 5 has won with 18 cards
Player 6 has won with 26 cards
Player 7 has won with 22 cards
Player 8 has won with 16 cards
Player 9 has won with 18 cards
Player 10 has won with 24 cards
으로
Player 6 has won with 24 cards
Player 10 has won with 24 cards
Player 7 has won with 22 cards
Player 4 has won with 20 cards
Player 2 has won with 18 cards
따라서 상위 5 명의 승자 (카드를 가장 많이 보유한 플레이어)에 대한 리더 보드를 만들어야합니다. 위의 텍스트는 원하는 출력입니다. 그런데이 리더 보드를 외부 텍스트 파일로 출력해야합니다.
내가 시도한 것 :
원시 텍스트를 다음과 같이 형식화하려고했습니다.
18 cards:Player 3 has won with 16 cards:Player 4 has won with 20 cards:Player 5 has won with 18 cards:Player 6 has won with 26 cards:Player 7 has won with 22 cards:Player 8 has won with 16 cards:Player 9 has won with 18 cards:Player 10 has won with 24 cards:
이렇게 한 후이 출력을 모든 콜론으로 분할하고 출력을 분할하는 변수를 인쇄했습니다.
내 코드 :
filereader = open("winner.txt", "r")
for everyline in filereader:
splittingvariable = everyline.split(":")
print(splittingvariable)
filereader.close()
출력 :
['player1 has won with 16 cards', 'player2 has won with 18 cards', 'player3 has won with 16 cards', 'player4 has won with 20 cards', 'player5 has won with 18 cards', 'player6 has won with 26 cards', 'player7 has won with 22 cards', 'player8 has won with 16 cards', 'player9 has won with 18 cards', 'player10 has won with 24 cards', '']
그러나 그 후 나는 무엇을 해야할지 몰랐다. 내가 보여준 것보다이 문제를 해결하기 위해 더 많은 노력을 기울 였지만 대부분은 오류가 발생했습니다.
이 문제를 해결하기위한 어떤 아이디어 나 방법도 대단히 감사하겠습니다.
먼저 최종 목록에서 빈 문자열 요소를 정리 한 후 다음 코드를 사용합니다.
res = ['player1 has won with 16 cards', 'player2 has won with 18 cards', 'player3 has won with 16 cards', 'player4 has won with 20 cards', 'player5 has won with 18 cards', 'player6 has won with 26 cards', 'player7 has won with 22 cards', 'player8 has won with 16 cards', 'player9 has won with 18 cards', 'player10 has won with 24 cards']
res.sort(key = lambda x: x.split()[4], reverse = True)
print(res[:5])
산출:
['player6 has won with 26 cards',
'player10 has won with 24 cards',
'player7 has won with 22 cards',
'player4 has won with 20 cards',
'player2 has won with 18 cards']
그것은 당신이 원하는 것입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다