【问题标题】:Formatting the output of a key from a dictionary格式化字典中键的输出
【发布时间】:2010-10-30 00:34:51
【问题描述】:

我有一个字典,它存储一个字符串作为键,一个整数作为值。在我的输出中,我希望将键显示为不带括号或逗号的字符串。我该怎么做?

for f_name,f_loc in dict_func.items():
        print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc))

输出:

Enter the file name: test.txt
line = 'def count_loc(infile):'

There were 19 lines of code in "test.txt"

Function names:

    ('count_loc(infile)',) -- 15 lines of code

如果不清楚,我希望输出的最后一行显示为:

count_loc(infile) -- 15 lines of code

编辑

name = re.search(func_pattern, line).groups()
name = str(name)

在我的输出之前使用 type(),我验证它仍然是一个字符串,但输出与 name 是一个元组时的输出一样

【问题讨论】:

    标签: python string dictionary python-3.x


    【解决方案1】:

    我没有 Python 3,因此无法对此进行测试,但 f_name 的输出使它看起来像是一个包含一个元素的元组。所以你要把.format(f_name, f_loc)改成.format(f_name[0], f_loc)

    编辑

    针对您的编辑,尝试使用.group() 而不是.groups()

    【讨论】:

      【解决方案2】:

      详细说明Peter's answer,在我看来,您正在分配一项tuple 作为字典的键。如果您在某处计算括号中的表达式并将其用作键,请确保其中没有杂散的逗号。

      查看您进一步编辑的答案,这确实是因为您正在使用正则表达式匹配的 groups() 方法。这将返回一个 (the entire matched section + all the matched groups) 的元组,并且由于您没有组,因此您想要整个事情。 group() 没有参数会给你。

      【讨论】:

      • 啊,我明白了我做了什么,但我仍然不确定如何解决它。当我获取函数的名称并使用正则表达式时,我使用了 .groups() 方法。我将在原始代码中添加它的代码,因为我将它转换为 str,它仍然产生相同的输出
      • 如果你使用 .groups(),请尝试使用 .group()
      【解决方案3】:

      我预计您的解析代码有问题。所写的行应该按预期工作。

      【讨论】:

        【解决方案4】:

        由于键是某种类型的元组,您可能希望在打印之前加入不同的元素。我们无法从显示的 sn-p 中真正看出密钥的意义。

        所以你可以这样做:

        .format(", ".join(f_name), f_loc)
        

        【讨论】:

          猜你喜欢
          • 2017-05-14
          • 2015-08-20
          • 1970-01-01
          • 2016-10-08
          • 2020-11-17
          • 2022-01-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多