【问题标题】:The cause of differences of "for" loop between list and dictionary列表和字典“for”循环差异的原因
【发布时间】:2018-02-23 22:34:21
【问题描述】:

我已经创建了一个列表的“for”循环。

chosen_subjects = ['physics', 'maths', 'computer science', 'medicine']

for subjects in chosen_subjects:
    print(subjects.title())

我已经做了一个字典的“for”循环

chosen_subjects = {'sarah': 'physics', 'john': 'maths', 'denise': 'computer science', 'william': 'medicine'}

for subjects in chosen_subjects.values():
    print(subjects.title())

这些代码的结果完全相同。

Physics
Maths
Computer Science
Medicine

基本上,如果你们看一下列表和字典的这两个“for”循环的“for”行,“for”循环的列表不需要冒号之前的括号,而“for”循环的字典冒号前需要括号。

程序的原因是什么,为什么python设计者在最初制作“for”循环时会在列表和字典之间做出如此明显的区别?

【问题讨论】:

  • values 是一个函数,你需要括号来调用它。
  • 在第一种情况下,您正在迭代变量chosen_subjects。在第二种情况下,您正在迭代通过调用方法chosen_subjects.values 返回的值。你用括号调用方法。
  • 具体来说,这不是“for”循环的工作方式不同。 “for”循环只需要被赋予一些可迭代的东西来迭代,你已经发现了几种不同的方法来获得可迭代的东西

标签: python list loops dictionary


【解决方案1】:

对于数组,目标非常简单:

[a, b, c, d, e]

您会希望 for 循环为您提供数组中的每个值。

对于字典:

{a:"cat", b:"dog", c:"moose"}

期望的行为不是那么明显。开发人员是否要遍历每个键? [a, b, c, d] 还是他们想要这些值? ["cat", "dog", "moose"].

这是因为字典没有明确的迭代方式。所以你必须指定你想如何迭代。这就是.values() 起作用的原因。您正在从字典中获取一组值。

【讨论】:

    猜你喜欢
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2017-04-05
    • 2020-06-10
    • 2015-06-25
    • 1970-01-01
    相关资源
    最近更新 更多