gpt4 book ai didi

python - str(list) 如何工作?

转载 作者:太空狗 更新时间:2023-10-29 17:51:44 26 4
gpt4 key购买 nike

为什么str(list)返回我们如何在控制台上看到列表?怎么样str(list)工作? (对 str(list) 的 CPython 代码的任何引用)?

>>> x = ['abc', 'def', 'ghi']
>>> str(x)
"['abc', 'def', 'ghi']"

str(list) 取回原始列表我必须:
>>> from ast import literal_eval
>>> x = ['abc', 'def', 'ghi']
>>> str(x)
"['abc', 'def', 'ghi']"
>>> list(str(x))
['[', "'", 'a', 'b', 'c', "'", ',', ' ', "'", 'd', 'e', 'f', "'", ',', ' ', "'", 'g', 'h', 'i', "'", ']']
>>> literal_eval(str(x))
['abc', 'def', 'ghi']

为什么不list(str(list))str(list)回到原来的名单?

或者我可以使用:
>>> eval(str(x))
['abc', 'def', 'ghi']

literal_evaleval ?是 eval使用安全吗?

我可以做多少次以下?如果继续执行,代码是否会中断 str(list(str(list)))) ? 例如。
>>> x = 'abc'
>>> list(x)
['a', 'b', 'c']
>>> str(list(x))
"['a', 'b', 'c']"
>>> list(str(list(x)))
['[', "'", 'a', "'", ',', ' ', "'", 'b', "'", ',', ' ', "'", 'c', "'", ']']
>>> str(list(str(list(x))))
'[\'[\', "\'", \'a\', "\'", \',\', \' \', "\'", \'b\', "\'", \',\', \' \', "\'", \'c\', "\'", \']\']'
>>> list(str(list(str(list(x)))))
['[', "'", '[', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'a', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'b', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'c', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ']', "'", ']']
>>> str(list(str(list(str(list(x))))))
'[\'[\', "\'", \'[\', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \'a\', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \',\', "\'", \',\', \' \', "\'", \' \', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \'b\', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \',\', "\'", \',\', \' \', "\'", \' \', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \'c\', "\'", \',\', \' \', \'"\', "\'", \'"\', \',\', \' \', "\'", \']\', "\'", \']\']'
>>> list(str(list(str(list(str(list(x)))))))
['[', "'", '[', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '[', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'a', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'b', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", 'c', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', "'", '"', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", '"', "'", ',', ' ', "'", ',', "'", ',', ' ', "'", ' ', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ']', "'", ',', ' ', '"', "'", '"', ',', ' ', "'", ']', "'", ']']

最佳答案

那么你总共有4个问题,让我们一一回答。

1. Why does str(list) returns how we see list on the console? How does str(list) work?



什么是 str() __str__() ?
str() callable 只是返回对象的可打印形式!来自 docs

str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string.


__str__()每当您调用 str() 时都会调用类中的函数在一个物体上。再次来自 documentation

object.__str__(self)

Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object.



什么是 list 可调用?
list() callable 是从作为参数传递的可迭代对象创建一个列表。再次来自 docs

Return a list whose items are the same and in the same order as iterable‘s items



因此, str(list)为您提供可打印的表格和 list(str(list))将遍历字符串。即 list(str(list))将为您提供所传递参数的可打印形式的单个字符的列表。

嵌套调用之间的一个小步骤,

给定列表, l = ['a','b'] (对于采用比您的问题中的示例更小的示例表示歉意)。

当您拨打 str(l) ,它返回列表 l 的可打印形式,即 "['a','b']" .

现在你可以清楚地看到 "['a','b']"是一个字符串,确实是一个可迭代的。现在当您拨打 list在这方面,即 list("['a','b']")你会得到一个奇怪的列表,比如 ['[', "'", 'a', "'", ',', "'", 'b', "'", ']'] .为什么会发生这种情况?发生这种情况是因为字符串迭代其字符,您可以使用虚拟字符串进行测试,
>>> 'dummy'
'dummy'
>>> list('dummy')
['d', 'u', 'm', 'm', 'y']

因此,当您拨打 list 时在一个字符串上,你会得到一个字符列表。再次注意,当您拨打 str() 时在 list('dummy') ,您将无法取回原始字符串 'dummy' ,所以你将不得不再次使用 join !因此,调用相同的函数将 不是 让你找回你的原始对象!

所以,拨打 str()通过列表调用内置 __str__()列表的方法?

答案是不!

当您拨打 str() 时内部会发生什么在名单上?

每当您调用 str()在列表对象上,遵循的步骤是
  • 调用 repr()每个列表元素。
  • 添加花式 [在前面和另一个]在列表的末尾。
  • 用逗号连接所有这些。

  • cpython on github中list对象的源码可以看出.在 hg.python 中浏览 cpython 的源代码,比较清楚,可以看下面三个评论。 (感谢 Ashwini 提供有关该特定 code 的链接)

    /* Do repr() on each element.  Note that this may mutate the list,
    so must refetch the list size on each iteration. */ line (382)

    /* Add "[]" decorations to the first and last items. */ line (398)

    /* Paste them all together with ", " between. */ line (418)


    这些对应于我上面提到的要点。

    现在是什么 repr() ?
    repr()打印所有对象的字符串表示。再次来自 documentation

    Return a string containing a printable representation of an object.



    还要注意这句话!

    For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.



    现在你的第二个问题,

    2. Why doesn't list(str(list)) turns the str(list) back to the original list?



    内部, str(list)实际上创建了 repr()列表对象的表示。所以要在拨打 str 后取回名单在列表中,您实际上需要做 eval 在它上面而不是 list称呼。

    解决方法

    但我们都知道 eval is evil ,那么解决方法是什么?

    1. 使用 literal_eval

    第一个解决方法是使用 ast.literal_eval .这就引出了你的第三个问题,

    3. Is literal_eval() the same as eval()? Is eval() safe to use?



    ast.literal_eval() 安全 unlike eval()功能。文档本身提到它是安全的——

    Safely evaluate an expression node or a string containing a Python literal or container display



    2. 使用字符串函数和内置函数

    另一种解决方法可以使用 str.split() 来完成
    >>> x = ['abc', 'def', 'ghi']
    >>> a = str(x)
    >>> a[2:-2].split("', '")
    ['abc', 'def', 'ghi']

    这只是对字符串列表执行此操作的一种简单方法。对于整数列表,您将需要 map .
    >>> x = [1,2,3]
    >>> a =str(x)
    >>> list(map(int,a[1:-1].split(', '))) # No need for list call in Py2
    [1, 2, 3]

    因此不像 literal_eval鉴于您知道列表的元素,这些是简单的技巧。如果它们本质上是异质的,例如 [1, "a", True]那么您将不得不遍历拆分列表并发现元素类型,然后对其进行转换并将转换后的元素附加到最终列表中。

    另一个失败的地方是字符串本身包含引号字符。正如 nneonneo 所提到的在 comment

    The str.split solution is very fragile and will break if the input contains e.g. strings that contain ", ", or tuples, or other lists, ... It is much better to use ast.literal_eval because that will deal with all the subtleties of the syntax.



    对于你的最后一个问题,

    4. Does the code break if you do str(list(str(list)))) again and again?



    并不真地。每次创建 list 时,输出会越来越长。的 str然后再次获得它的可打印版本。限制仅是您的物理机的限制。 (很快就会达到字符串长度乘以 5 的每一步。)

    关于python - str(list) 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30109030/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com