2016-01-18 71 views
2
Enter your name, age & score: a 17 99 

Enter your name, age & score: a 19 98 

Enter your name, age & score: a 19 100 

Enter your name, age & score: a 19 99 

Enter your name, age & score: b 19 99 

Enter your name, age & score: b 19 98 

Enter your name, age & score: b 19 100 

Enter your name, age & score: -1 

输出:我该怎么办元组排序

(('a', '17', '99'), ('a', '19', '100'), ('a', '19', '98'), ('a', '19', '99'), ('b', '19', '100'), ('b', '19', '98'), ('b', '19', '99')) 

输出应该是这样的:

(( 'A', '17', '99'),(” ('a','19','98'),('a','19','99'),('a','19','100'),('b','19',' ('b','19','99'),('b','19','100'))

我该怎么做?这是我的代码..

def check(txt): 
    global c 
    if txt.count(" ") == 2: 
     tup=(tuple(txt.split(" "))) 
     list1.append(tup) 
     list1.sort() 
    else: 
     if txt != "-1": 
      c= 1 
      return c 
main() # prints the converted list to tuple.. 
+1

我你如何试图对它们进行排序不清楚。 – miradulo

+2

获取该输出的规则是什么?你的输出对我没有任何意义 – SirParselot

+5

为什么99,98,100? –

回答

1

尝试sorted

sorted(your_tup, key=lambda x: [x[0], int(x[1]), int(x[2])]) 
+0

我试过这个和工作。但我真的不明白这是如何工作哈哈 – eshi

+0

排序将采取'键'==>'指定一个参数,用于从每个列表元素提取比较键的函数。在此之前,比较每个元素中的键转换2nd和3rd项为int。 – Praveen

+0

首先,你是否明白为什么原始产量是原样? –

1

元组排序正确,因为它们只包含字符串。如果你想通过数字来排序,存储值作为整数:

parts = txt.split(" ") 
list1.append(tuple(parts[0], int(parts[1]), int(parts[2]))