根据某一特征对对象列表进行分组
我有一个对象列表(在这个例子中是字符串),我想根据一个函数返回的特征来对它们进行分类。
比如,考虑下面这个列表:
['sky', 'ocean', 'grass', 'tomato', 'leaf']
还有一个函数 color(item)
,它会返回传入字符串的颜色,比如 color('sky')
会返回 'blue'
。我现在想把这个列表转换成一个字典或者一个列表的列表,按照颜色(也就是函数返回的值)来分组这些项目。可能的结果看起来像这样:
{
'blue': ['sky', 'ocean'],
'green': ['grass', 'leaf'],
'red': ['tomato']
}
我不在乎具体的键是什么,只要这些项目能够按照颜色分组就可以了,所以嵌套列表也没问题。我只是想用一种“python风格”的方式来做到这一点 :)
3 个回答
0
稍微修改一下' unwind '提出的解决方案:
a = ['sky', 'ocean', 'grass', 'tomato', 'leaf']
def color(x):
# dummy hash function for demo
return len(x)
color_map = {}
for x in a:
key = color(x)
color_map.setdefault(key,[]).append(x)
print color_map
上面的代码示例会输出:
{3: ['sky'], 4: ['leaf'], 5: ['ocean', 'grass'], 6: ['tomato']}
0
a = ['sky', 'ocean', 'grass', 'tomato', 'leaf']
sa = {}
for x in a:
key = color(x)
if key in sa:
sa[key].append(x)
else:
sa[key] = [x]
我不太确定这算不算“pythonic”(符合Python风格),但这个方法挺清晰的。在较新的Python版本中,你可以使用默认字典,这样可以让循环的主要部分看起来更简洁。
5
我觉得可以这样来理解这个问题:
from collections import defaultdict
D = defaultdict(list)
a = ['sky', 'ocean', 'grass', 'tomato', 'leaf']
for item in a:
D[color(item)].append(item)
这样你就得到了一个以颜色为键的字典,每个键对应一个列表,里面包含了属于那个类别的项目。