2017-01-23 86 views
-2

此代码通常所说的最小数量在列表前面在输入的名单,但由于某些原因,每当122被inputed像这样Please enter your cards(x, y, z,...): 12, 2它输出为什么python在排序列表时称12 <2?

12, 2 
12, 2 

下面是代码:

#!/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

您目前正在比较数字作为STRINGS,例如:'12'<'2'。

因为'12'在进行字符串比较时('1'的数值小于'2'),因此'012'为<'',这意味着评估看起来很时髦。

你想要做的是比较这些数字的整数值,例如:

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