Skip to main content
 首页 » 编程设计

Python数组排序

2025年05月04日16over140

我想对列表进行排序,以便将列表的属性输入到循环中。让我详细说明:

假设我有:

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 

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

请您参考如下方法:

构建一个包含每个动物穿着的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']