从print语句中识别基础数据集(Identifying the underlying dataset from the print statement)

编程入门 行业动态 更新时间:2024-10-27 09:37:27
从print语句中识别基础数据集(Identifying the underlying dataset from the print statement)

我正在学习Python,并希望从print语句的显示中识别数据结构。 我写了以下代码:

set1={1,2,3,3} print set1 tup1=(1,2,3,3) print tup1 list1=[1,2,3,3] print list1 dict1={1:1,2:2,3:3,3:3} print dict1

输出是:

set([1, 2, 3]) (1, 2, 3, 3) [1, 2, 3, 3] {1: 1, 2: 2, 3: 3}

从这里我推断set1是一个python集,tup1是一个python元组,list1是一个python列表,dict1是一个python字典。

我们能否以通用方式使用此类比来从print语句中识别基础数据结构?

I am learning Python and wanted to identify the data structure from the display of print statement. I wrote the following code:

set1={1,2,3,3} print set1 tup1=(1,2,3,3) print tup1 list1=[1,2,3,3] print list1 dict1={1:1,2:2,3:3,3:3} print dict1

And the output is:

set([1, 2, 3]) (1, 2, 3, 3) [1, 2, 3, 3] {1: 1, 2: 2, 3: 3}

From this I infer that set1 is a python set, tup1 is a python tuple, list1 is a python list and dict1 is a python dictionary.

Can we use this analogy in a generalized way to identify the underlying data structure from the print statement?

最满意答案

您正在查看repr()函数的输出。 它取决于对象本身提供有意义的object.__repr__()方法 ; 内置类型产生有效的Python语法,可以让你重现相同的值,但对于Python类, repr()输出并不总是有用:

>>> class Foo(object): ... def __init__(self, bar): ... self.bar = bar ... >>> print Foo(42) <__main__.Foo object at 0x102312990>

这只会告诉您具有哪种类型的实例,而不是如何重现相同的值。

如果您只想知道类型 ,请使用type()函数 :

>>> type(Foo(42)) <class '__main__.Foo'> >>> type({1, 2, 3}) <type 'set'>

You are looking at the output of the repr() function. It is up to the object itself to provide a meaningful object.__repr__() method; the built-in types produce valid Python syntax that'll let you reproduce the same value, but for Python classes the repr() output is not always as helpful:

>>> class Foo(object): ... def __init__(self, bar): ... self.bar = bar ... >>> print Foo(42) <__main__.Foo object at 0x102312990>

This only tells you what type of instance you have, not how reproduce the same value.

If all you want to know is the type, use the type() function:

>>> type(Foo(42)) <class '__main__.Foo'> >>> type({1, 2, 3}) <type 'set'>

更多推荐

本文发布于:2023-07-04 10:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023086.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   基础   数据   print   statement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!