【问题标题】:How is the current element of an iteration related to the iterator?迭代的当前元素与迭代器有什么关系?
【发布时间】:2019-11-22 14:13:23
【问题描述】:

考虑以下代码:

mylist = [
    {'a': 1},
    {'b': 2},
]

for el in mylist:
    print(mylist)
    x, y = el.popitem()
    print(x, y)

我希望mylist 不会更改迭代(因此在打印时每次都相同),因为我正在处理作为当前迭代元素的变量,为什么要这样做。

输出是

[{'a': 1}, {'b': 2}]
a 1
[{}, {'b': 2}]
b 2

这意味着弹出迭代的当前值会影响迭代器本身。为什么会这样? (我猜这是因为当前元素是指向列表中元素的指针)

我应该如何迭代以使迭代列表不改变? (我需要popitem()当前元素来收集它的键和值)

【问题讨论】:

  • 只是为了你的熏陶mydict其实是list
  • 变量el 是列表中对象的名称(mydict 是一个容易混淆的名称)。
  • @That1Guy:好的,我改了名字——我最初对这个例子有另一个想法
  • @PeterWood:好的,我改了名字——我最初对这个例子有另一个想法
  • 这里的预期输出是什么?你可以做for el in mylist: for key, value in el.items()

标签: python python-3.x iterator


【解决方案1】:

el 变量是对列表中值的引用是正确的。

您可以使用.items() 从字典中获取键值对

mydict = [
    {'a': 1},
    {'b': 2},
]

for el in mydict:
    print(mydict)
    x, y = list(el.items())[0] # This assumes that you only have 1 pair in the list, otherwise it will return the first one
    print(x, y)

【讨论】:

    【解决方案2】:

    当您调用popitem 时,您正在修改元素(dict),所以当您第二次打印时,它是空的。

    mylist = [
        {'a': 1},
        {'b': 2},
    ]
    
    for el in mylist:
        print(mylist) # First iteration:  [{'a':1},{'b':2}]
                      # Second iteration: [{},{'b':2}] because the first iteration removed el ({'a':1})
        x, y = el.popitem() # Remove the items from the dict el
        print(x, y)
    

    el 只是一个指向元素的指针,所以如果你修改它,它会在包含列表中被修改。

    您始终可以使用dictitems 方法:

    for el in mylist:
        print(mylist)
        #x, y = el.items()[0] # Python 2
        x, y = list(el.items())[0] # Python 3
        print(x, y)
    

    items 将键值对作为元组列表返回而不将它们从字典中删除

    【讨论】:

      猜你喜欢
      • 2011-02-13
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多