【问题标题】:Why is the ipython output of set different from the __repr__ or __str__ of the set? [duplicate]为什么 set 的 ipython 输出与 set 的 __repr__ 或 __str__ 不同? [复制]
【发布时间】:2016-06-14 17:56:24
【问题描述】:

我在 ipython 中运行以下代码,对代码的打印输出和 ipython 单元格输出感到惊讶:

print set(["A", "B", "C"])
print set(["A", "C", "B"])
print list(set(["A", "C", "B"]))
print list(set(["A", "B", "C"]))
print [k for k in set(["A", "C", "B"])]
print [k for k in set(["A", "B", "C"])]
a = set(["A", "B", "C"])
print a
print a.__repr__()
print a.__str__()
print [(k, hash(k)) for k in a]
a

上述程序的输出如下:

set(['A', 'C', 'B'])
set(['A', 'C', 'B'])
['A', 'C', 'B']
['A', 'C', 'B']
['A', 'C', 'B']
['A', 'C', 'B']
set(['A', 'C', 'B'])
set(['A', 'C', 'B'])
set(['A', 'C', 'B'])
[('A', -269909568), ('C', -13908798), ('B', -141909181)]
Out[34]: {'A', 'B', 'C'}

注意,单元格输出为{'A', 'B', 'C'},而打印输出为set(['A', 'C', 'B'])

我的Python详情如下:

import sys
print sys.version
2.7.11 |Anaconda 2.3.0 (64-bit)| (default, Jan 29 2016, 14:26:21) [MSC v.1500 64 bit (AMD64)]

【问题讨论】:

    标签: python python-2.7 ipython


    【解决方案1】:

    那是因为set 是一个无序序列。当您定义set 时,它是无序的。当您尝试打印它时,它需要想出某种方式对其进行排序,但这与给定set 的元素的顺序无关。此外,当您尝试从set 创建list 时,它需要提出一些命令。它得出的顺序总是相同的,但与给定元素的顺序完全无关。

    【讨论】:

      【解决方案2】:

      IPython 不时添加一些魔法来使内容更具可读性。

      在这种情况下,它向您展示了一个集合文字(python2.7 中的新功能)

      下面是实现这一点的代码:

      https://github.com/ipython/ipython/blob/f49962dc931870a1eba4b6467ce302c8ae095b3f/IPython/lib/pretty.py#L560

      【讨论】:

        【解决方案3】:

        IPython 使用不同的打印函数:

        In [1]: from IPython.lib.pretty import pprint
        
        In [2]: a = set(["A", "B", "C"])
        
        In [3]: pprint(a)
        {'A', 'B', 'C'}
        
        In [4]: a
        Out[4]: {'A', 'B', 'C'}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-11
          • 2017-05-18
          • 1970-01-01
          • 2012-09-14
          • 2013-08-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多