0

我有一个 list 的列表,s它是查询 Fruit 数据库的结果,item[0]是水果的名称,是水果item[1]是否有种子,item[2]是它是否可食用。

s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]

由于我的实际列表要大得多,我想要一种非常简单的方法来引用/返回这些值。例如,print my_dict['Apple']['Seeds']将产生Yes

我认为我最好的选择是创建一个字典,但我正在寻找关于这是否是一个好方法以及如何做到这一点的建议。

我开始编写一些代码,但不确定如何获得第二组标头,因此我的示例使用了索引。

my_dict =  {t[0]:t[1:] for t in s}

print my_dict['Apple'][0]
4

3 回答 3

5
fruit_map = {
    fruit: {'Seeds': seeds, 'Edible': edible} for fruit, seeds, edible in s}
于 2015-01-19T23:35:47.797 回答
2

如果第二组键永远不会改变,那么最好定义一个带有字段的适当对象。这可能看起来有点矫枉过正或冗长,但总collections.namedtuple有帮助。

namedtuple从字段名称列表中创建一个新类。该类还支持由列表初始化。要使用您的示例:

import collections

Fruit = collections.namedtuple('Fruit', ['name', 'seeds', 'edible'])

这样,您可以轻松地Fruit从列表中创建对象:

f = Fruit('Apple', True, False)
# Or, if you already have a list with the values
params = ['Apple', True, False]
f = Fruit(*params)

print f.seed

因此,您可以以非常简单的方式创建水果列表:

s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]

fruits = [Fruit(*l) for l in s]

你真的需要有一个由某个字段索引的字典,它没有太大的不同:

s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]

fruit_dict = {l[0]: Fruit(*l) for l in s}    
print(fruit_dict['Apple'].seeds)

namedtuples 在将值列表转换为更易于使用的对象时非常方便(例如在读取 CSV 文件时,这与您所要求的情况非常相似)。

于 2015-01-19T23:35:55.403 回答
0
import copy

def list_to_dict(lst):
    local = copy.copy(lst) # copied lst to local
    fruit = [i.pop(0) for i in local] # get fruit names

    result = {}
    for i in range(len(local)):
        result[fruit[i]] = local[i]
    return result

这将返回您想要的字典。

于 2015-01-19T23:51:18.943 回答