【问题标题】:How can I create a dictionary within a function?如何在函数中创建字典?
【发布时间】:2019-01-16 13:29:11
【问题描述】:

我想在我的函数中创建一个字典,但我不能。我找到的唯一可能的解决方案是在函数之外和调用它之前创建字典的名称。

argentina = {}
def get_dic(file,phone):
    for line in file.readlines():
        if (line[0] == '#'):
            names = line.rstrip().strip()
            phone[names] = ''
        else:
            phone[names] = phone[names] + line.rstrip().strip()

get_dic(open(sys.argv[1],'r'), argentina)

get_dic(open(sys.argv[1],'r'), argentina) 将打开一个名为'argentina' 的字典,但我不需要提前创建argentina = {}

【问题讨论】:

  • 你试过return从函数中输入字典吗?
  • 另外,nameselse 中未定义(或者更确切地说,是上次迭代的值——或者这是故意的?)并且rstrip().strip() 是多余的。
  • 谢谢! .为什么 rstrip().strip() 是多余的?
  • 它是多余的,因为它首先从字符串的右侧去除空格,然后从两侧去除。

标签: python function dictionary


【解决方案1】:

只需在里面创建字典并从函数中返回它:

def get_dic(file):
    phone = {}
    names = None
    for line in file.readlines():
        if line[0] == '#':
            names = line.strip()
            phone[names] = ""
        else:
            phone[names] += line.strip()
    return phone

argentina = get_dic(open(sys.argv[1],'r'))

【讨论】:

  • 仔细观察,可能是故意在if 中设置names,以便在以# 开头的行中累积行中的行...
猜你喜欢
  • 2015-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
相关资源
最近更新 更多