【问题标题】:Python - struggling to print in the following format using dictionaryPython - 努力使用字典以以下格式打印
【发布时间】:2021-03-02 16:29:21
【问题描述】:

我打印了一些如下所示的代码:

print(len(no_of_records))

200
150
2000

我有一个像这样的字典列表:

list_names = {
    "Yellow_List": "yellow",
    "Blue_List": "blue",
    "Red_List": "red"
}

我希望能够在字典中打印我的键名,记录数如下:

The yellow list has 200
The blue list has 150
The red list has 2000

我试过了

for key in list_names:
    print("The", key, "has", len(no_of_records))

但我得到了:

The yellow list has 200
The blue list has 200
The red list has 200
The yellow list has 150
The blue list has 150
The red list has 150
The yellow list has 2000
The blue list has 2000
The red list has 2000

【问题讨论】:

  • 什么是 no_of_records?你也可以分享那个代码吗?
  • 您能提供更多代码吗?很难看到发生了什么。您是否在列表中的每个列表名称都出现了 3 次?您发布的 for 循环是否被另一个 for 循环包围?我不明白为什么 len(no_of_records) 应该在循环内完全改变。它将打印相同数字的 3 倍。它似乎是这样做的,但它又做了 3 次。这就是为什么我要询问周围的 for 循环。
  • 除非您在 print(len(num_of_records)) 中有一个 for 循环,否则不应打印 3 个不同的值。如果 num_of_records 是 list_names 的相同 len 的列表,则 zip 函数应该足够了。但是您的问题缺少重要信息,以使其易于理解。

标签: python python-3.x list printing


【解决方案1】:

你可以这样做:

no_records = [200, 150, 2000]
list_names = {
    "Yellow_List": "yellow",
    "Blue_List": "blue",
    "Red_List": "red"
}

for key, x in zip(list_names.values(), no_records):
    print('The', key, 'list has', x)
The yellow list has 200
The blue list has 150
The red list has 2000

【讨论】:

  • 我宁愿将 no_records 的输出与键结合起来,而不是将其包含在代码中,因为这些数字可能会改变 :)
  • 你是对的,但是 OP 没有提供对象no_of_records。
猜你喜欢
  • 1970-01-01
  • 2017-08-27
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 2017-01-01
  • 2020-08-27
相关资源
最近更新 更多