【问题标题】:No shortcut : save dict to file / count items in dict没有快捷方式:将字典保存到文件/计算字典中的项目
【发布时间】:2017-03-09 07:15:39
【问题描述】:

Python 3

大家好,我现在是学习字典的python初学者

以下是我到目前为止所学到的如何将列表保存到文件中

并计算列表中的项目,如下所示。

class item:
    name = None
    score = None

def save_list_in_file(file_name:str, L:[item]):
    f = open(file_name,'w')
    for it in L:
        f.write(it.name + "" + str(it.score))
    f.close()

def count_item_in_list(L:[item])->int:
    n = 0
    for it in L:
        if it.score >= 72:
        n += 1
    return n

我不确定使用字典是否与我在列表中使用的方式相同

例如:

def save_dict_to_file(file_name:str, D:{item}):
    f = open(file_name,'w')
    for it in D:
        f.write(it.name + "" + str(it.score))
    f.close()

def count_item_in_dict(D:{item})->int:
    n = 0
    for it in D:
        if it.score <= 72:
        n += 1
    return n

会是正确的吗?我认为 dict 与使用列表不同。

感谢您的任何评论!

【问题讨论】:

  • oops 没有捷径意味着我不能使用简单的模块。

标签: python-3.x dictionary


【解决方案1】:

您不能像使用列表一样使用字典。

列表被定义为一系列元素。所以当你有列表时:

    L=['D','a','v','i','d']

你可以这样循环:

    for it in L:
        print(it)

它会打印出来:

  D
  a
  v
  i
  d

相反,字典是一组包含两个元素的元组,其中一个是键,第二个是值。例如,你有一个这样的字典:

    D = {'firstletter' : 'D', 'secondletter': 'a', 'thirdletter' : 'v' }

当你像一个列表一样循环它时:

    for it in L:
        print(it)

它只会打印键:

    firstletter
    secondletter
    thirdletter

所以为了获得你必须像这样打印它的值:

    for it in D:
        print(D[it])

将显示此结果:

D
a
v

如果您需要更多信息,可以查看字典的文档:)

Python 3 documentation of Data Structures

【讨论】:

    猜你喜欢
    • 2022-09-28
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2017-07-14
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    相关资源
    最近更新 更多