2014-04-16 16 views
0
data = set(['booklet', '4 sheets', '48 sheets', '12 sheets',44,443 ,'$sdsds', '>>>>ASdasdas']) 
r = sorted(data, key=lambda item: (int(item.partition(' ')[0]) 
            if item[0].isdigit() else float('inf'), str(item))) 
print ',\n'.join(r) 

我:蟒蛇字母排序沒有給出相應的「INT(STR)」超載發現:以下重載可

Traceback (most recent call last): 
    File "test.py", line 2, in <module> 
    r = sorted(data, key=lambda item: (int(item.partition(' ')[0]) 
    File "test.py", line 3, in <lambda> 
    if item[0].isdigit() else float('inf'), str(item))) 
TypeError: 'int' object has no attribute '__getitem__' 

如何使這種工作?

+0

預期產量是多少? – thefourtheye

+0

你能具體嗎? – thefourtheye

+6

這很奇怪。我沒有得到SyntaxError,我得到'TypeError:'int'對象不是可以下載的。無論如何,當'item'是44時,在它上面調用'partition'或者執行'item [0]'是沒有意義的,因爲它不是一個字符串。 – Kevin

回答

1

您不能下標整數,因爲它們不可迭代。這就是你在做44[0]時所要做的。

你很可能意味着:

str(item)[0].isdigit() 
2

你想要這個???

In [12]: r = sorted(data, key=lambda item: (int(str(item).partition(' ')[0])if str(item)[0].isdigit() else float('inf'), str(item))) 

In [13]: r 
Out[13]: 
['4 sheets',                               
'12 sheets',                               
44,                                 
'48 sheets',                               
443,                                 
'$sdsds',                                
'>>>>ASdasdas',                              
'booklet']