这是我的做法:
higher_order_conversion = {
('apple', 'pear', 'kiwi'): 'fruit', #the keys must be tuples, not lists
('X', 'Y', 'Z'): 'letter', # (because tuples are immutable and therefore hashable)
('loafers', 'sneakers', 'high heels'): 'shoes'
}
data_set = [[125, 'apple'], #these numbers are id numbers, or whatever extra information you might have packaged with your data
[126, 'Y'],
[127, 'loafers'],
[103, 'kiwi']
]
print 'before', data_set
for data in data_set:
for lower_order_list in higher_order_conversion.keys():
if data[1] in lower_order_list:
data[1] = higher_order_conversion[lower_order_list]
print 'after', data_set
输出:
before [[125, 'apple'], [126, 'Y'], [127, 'loafers'], [103, 'kiwi']]
after [[125, 'fruit'], [126, 'letter'], [127, 'shoes'], [103, 'fruit']]
希望这能给你一些想法。