【问题标题】:What does <for> and <in> do together in python [duplicate]<for> 和 <in> 在python中一起做什么[重复]
【发布时间】:2018-09-15 13:54:15
【问题描述】:

这是我的 Python 代码

thisdict =  {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

thisdict["year"] = 2018
for x in thisdict:
   print(x)

它输出:

brand
model
year

我看不懂逻辑!!

【问题讨论】:

  • for x in thisdict 产生一个字典键序列。
  • 你搜索过“python for in”吗?有一百万个教程涵盖了这一点。
  • @PeterWood 哪种序列?
  • Yash,什么样的序列有关系吗?
  • 你可以看到输出是字典的键列表,不是吗?

标签: python for-loop


【解决方案1】:

for a in b 迭代b,首先调用iter(b)以获取b的迭代器,然后在迭代器上重复调用next()并将值分配给a在运行循环体之前。

python 字典的迭代器会生成其所有 ,因此您将在循环中获取 thisdictx 的所有键并打印它们。

【讨论】:

    【解决方案2】:

    for loop 循环遍历 dictionary 中的键。要遍历并获取您可以执行的每个键的值 (Try it online):

    for x in thisdict:
       print(thisdict[x])
    

    它会输出:

    Ford
    Mustang
    2018
    

    【讨论】:

    • @roganjosh Nope 2018 是正确的,因为值已更改
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多