Python中字典的使用

2024-09-30 04:30:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个概念学习程序,我需要从索引转换为类别名称。在

例如:

# binary concept learning
# candidate eliminaton learning algorithm
import numpy as np
import csv

def main():
    d1={0:'0', 1:'Japan', 2: 'USA', 3: 'Korea', 4: 'Germany', 5:'?'}
    d2={0:'0', 1:'Honda', 2: 'Chrysler', 3: 'Toyota', 4:'?'}
    d3={0:'0', 1:'Blue', 2:'Green', 3: 'Red', 4:'White', 5:'?'}
    d4={0:'0', 1:1970,2:1980, 3:1990, 4:2000, 5:'?'}
    d5={0:'0', 1:'Economy', 2:'Sports', 3:'SUV', 4:'?'}

    a=[0,1,2,3,4]
    print a

if __name__=="__main__":
    main()

因此[0,1,2,3,4]应该转换为['0', 'Honda', 'Green', '1990', '?']。什么是最Python式的方法?在


Tags: import程序numpy名称maingreen类别algorithm
3条回答

我想你需要一个基本的字典速成课程:

这是一本合适的词典:

>>>d1 = { 'tires' : 'yoko', 'manufacturer': 'honda', 'vtec' : 'no' }

你可以很容易地在字典里称不可侵犯的东西:

^{pr2}$

字典分为两个不同的部分,键和值

testDict = {'key':'value'}

你使用字典的方式与列表完全相同:

>>>test = {0:"thing0", 1:"thing1"} #dictionary
>>>test[0]
'thing0'

这和刚才说的差不多

>>>test = ['thing0','thing1'] #list
>>>test[0]
'thing0'

在您的特定情况下,您可能希望正确格式化词典(我建议使用类似masterdictionary = {'country': ['germany','france','USA','japan], 'manufacturer': ['honda','ferrarri','hoopty'] } etcetera的方法,因为您可以更轻松地调用每个单独的条目

用同一本字典:

>>>masterdictionary['country'][1]
'germany'

是什么 dictionaryName['key'][iteminlistindex]

当然,没有什么可以阻止您将字典作为值放在字典中。。。。其他字典的内部值。。。在

您已经得到了直接问题的答案,但您可能希望考虑重新构建数据结构。对我来说,下面的内容更有意义,它将使您能够更容易地索引到您所询问的内容以及以后可能的任何查询:

from pprint import pprint

items = [[el.get(i, '?') for el in (d1,d2,d3,d4,d5)] for i in range(6)]
pprint(items)

[['0', '0', '0', '0', '0'],
 ['Japan', 'Honda', 'Blue', 1970, 'Economy'],
 ['USA', 'Chrysler', 'Green', 1980, 'Sports'],
 ['Korea', 'Toyota', 'Red', 1990, 'SUV'],
 ['Germany', '?', 'White', 2000, '?'],
 ['?', '?', '?', '?', '?']]

您可以:

data = [d1,d2,d3,d4,d5]
print [d[key] for key, d in zip(a, data)]

函数^{}可用于组合成iterables;在本例中为list。在

相关问题 更多 >

    热门问题