我想对列表进行排序,以便我可以将列表的属性输入到循环中。让我解释: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
我的想法是对数组进行排序,使相关的龟所有的东西可以被放入一个单独的列表。然后将其分开,但我对列表的了解很少。所以任何帮助或转发到有用的链接非常感谢。我希望这是一个很好的基本示例来表达我的需求。
你确定你不想要一个字典 - >列表映射吗? – FatalError
我将在数组中呈现数据。如果使用你的建议更容易,我很想听听如何使用它。 –
'sorted(list(map(operator.itemgetter(1),filter(lambda x:x [0] =='turtle',data))))'。哦,是的,不要忘记导入运营商 – khachik