2014-06-06 54 views
1

我想对列表进行排序,以便我可以将列表的属性输入到循环中。让我解释:Python数组排序

比方说,我有:

data = [('turtle', 'sock'), ('frog', 'hat'), ('turtle', 'shirt'), ('frog', 'boot')] 

,我只希望这都涉及到'turtle'元组,所以我想:

newdata = [('turtle', 'sock'), ('turtle', 'shirt')] 

然后我希望把'sock''shirt'在列表中,以便我可以做类似的事情:

lst = ['sock', 'shirt'] 

然后,我可以做这样的事情

print "what is the turtle wearing?" 
for item in lst: 
    print "the turtle is wearing a " + item 

我的想法是对数组进行排序,使相关的龟所有的东西可以被放入一个单独的列表。然后将其分开,但我对列表的了解很少。所以任何帮助或转发到有用的链接非常感谢。我希望这是一个很好的基本示例来表达我的需求。

+2

你确定你不想要一个字典 - >列表映射吗? – FatalError

+0

我将在数组中呈现数据。如果使用你的建议更容易,我很想听听如何使用它。 –

+0

'sorted(list(map(operator.itemgetter(1),filter(lambda x:x [0] =='turtle',data))))'。哦,是的,不要忘记导入运营商 – khachik

回答

6

这也可能是最合适的,以建立一个dict保存了每个动物穿(正如我在评论中提及):

from collections import defaultdict 

data = [('turtle', 'sock'), ('frog', 'hat'), ('turtle', 'shirt'), ('frog', 'boot')] 

d = defaultdict(list) 
for animal, clothing in data: 
    d[animal].append(clothing) 

print d['turtle'] 
+0

是的,我喜欢这个! –

0
data = [('turtle', 'sock'), ('frog', 'hat'), ('turtle', 'shirt'), ('frog', 'boot')] 

def function(key): 
    listWithKey = [] 
    for element in data: 
     if element[0] == key: 
      listWithKey.append(element[1]) 
    return listWithKey 

print(function("turtle")) 

这仅仅是使用列表和循环更基本的方法。输出是['sock', 'shirt']

+0

这种方法可以使用列表解析更简单地编写。 '[x [1] for x in data if x [0] =='turtle']' –