【问题标题】:Understanding one line for loop dictionary to panda in python3在python3中理解循环字典到熊猫的一行
【发布时间】:2021-01-09 03:36:08
【问题描述】:

我已经阅读了有关这方面的几个 StackOverflow 主题以及 Google。这不是我的代码。它是为 Python2 编写的。我试图理解 Python 3 中给出和错误的一行。我很难将我的头绕在这一行 for 循环上。

para['row_colors'] = pd.DataFrame([dict({'index': row}.items() + row_colors[row].items()) for row in table.index]).set_index('index')'

'row' 是用作键的示例名称。我明白了。 那个'+'正在抛出错误。不能做 dict.item + dict.item。我不明白正在构建的字典的结构。

【问题讨论】:

  • 你能分享你从哪里得到它的链接吗?或者在python3中运行时的错误信息是什么?

标签: python python-3.x dictionary python-2.x


【解决方案1】:

是的,因为dict.items() 在 Python 3 中不再返回列表,而是返回一个特殊对象,该对象充当字典中项目的类似集合的 view(与 @ 相同) 987654323@ 和 .values)。最简单的解决方法就是执行list(dict.items())

但是,在这种特殊情况下,dict({'index': row}.items() + row_colors[row].items()) 在 python 3 中可能只是 {'index':row, **row_colors[row]}

所以你可以使用:

para['row_colors'] = pd.DataFrame([{'index': row, **row_colors[row]} for row in table.index]).set_index('index')'

使用更现代的语法。

要了解以前的版本在做什么,请注意dict 构造函数接受可迭代的键值对:

>>> dict([('a', 1), ('b', 2)])
{'a': 1, 'b': 2}

由于 .items() 用于返回键值对列表,因此您可以执行类似的操作

dict(d1.items() + d2.items())

合并两个字典。要将其音译为 Python 3,您需要类似以下内容:

>>> d1 = {'foo': 'bar', 'baz': 'zing'}
>>> d2 = {"apple": 42}
>>> dict(list(d1.items()) + list(d2.items()))
{'foo': 'bar', 'baz': 'zing', 'apple': 42}

但是python 3有更方便的语法,你可以这样做:

>>> {**d1, **d2}
{'foo': 'bar', 'baz': 'zing', 'apple': 42}

或者,更灵活地使用特定的键值对:

>>> {'index': 'column1', **d1, 'frob': 'bob', **d2}
{'index': 'column1', 'foo': 'bar', 'baz': 'zing', 'frob': 'bob', 'apple': 42}

最后,请注意 Python 3.9 will be adding the | operator as a merge operator for dicts,允许非常简洁:

>>> d1 | d2
{'foo': 'bar', 'baz': 'zing', 'apple': 42}

对于最简单的情况

【讨论】:

  • 请注意,一个不错的 Python 编辑器 / IDE 会给出一个解释问题的警告。例如,PyCharm 警告:“类 'ItemsView' 没有定义 'add',因此不能在其实例上使用 + 运算符。”此处给出的解决方案是该问题的正确解决方案。
  • 谢谢。我想我跟着你。这一班轮正在使用两个列表构建键:值对。 Python 2 为 dict.items() 返回了一个列表,并且 list+list 是有效的。我现在看到了 ** 语法。我会再玩一些这个,看看我能不能让它自己工作。我接受你写的作为答案。
猜你喜欢
  • 2017-10-12
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 2021-07-17
  • 2018-04-19
相关资源
最近更新 更多