2017-01-23 2 views
-2

このコードは、通常、リストの前でinputedリストの中で最も小さい番号を置きますが、それはここでリストをソートするときにPythonが12 <2と言っているのはなぜですか?

12, 2 
12, 2 

を出力し、Please enter your cards(x, y, z,...): 12, 2122が同じようinputedされているたびに、いくつかの理由のためのコードです。

#!/usr/bin/python2.7 
cards_input = raw_input("Please enter your cards(x, y, z, ...): ") 
print cards_input 
cards = cards_input.split(", ") 

minimum = min(cards) 
cards.remove(min(cards)) 
cards.insert(0, minimum) 

print cards 

どうすればこの問題を解決できますか?

+7

あなたは、文字列ではなく数値を比較しています。比較する前に文字列を数値に変換するには 'int()'を使います。 – Barmar

+0

「ab」<'b''と同じ理由があります。 – melpomene

+0

[Pythonは文字列とintをどう比較するのですか?](http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int) – MSeifert

答えて

6

現在、数字はSTRINGとして比較されています(例: '12' < '2')。

'12'は< '2'なので、文字列比較( '1'の数値が '2'より小さい)の場合、評価がファンキーに見えます。

やりたいことなど、これらの数値の整数値を比較します

int('12') < int('2') 
次にあなたのコードを変更し

#!/usr/bin/python2.7 
cards_input = raw_input("Please enter your cards(x, y, z, ...): ") 
print cards_input 
cards = [int(x) for x in cards_input.split(", ")] 

minimum = min(cards) 
cards.remove(min(cards)) 
cards.insert(0, minimum) 

print cards 
関連する問題