gpt4 book ai didi

Python 你为什么要使用 [ :] over =

转载 作者:IT老高 更新时间:2023-10-28 22:21:32 25 4
gpt4 key购买 nike

我正在学习 python,我正在学习 https://developers.google.com/edu/python/strings 上的教程

字符串切片部分下

s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the pythonic way to copy a sequence like a string or list)

出于好奇,您为什么不直接使用 = 运算符?

s = 'hello';
bar = s[:]
foo = s

据我所知 barfoo 具有相同的值。

最佳答案

= 进行引用,通过使用 [:] 创建一个副本。对于不可变的字符串,这并不重要,但对于列表等来说,这很重要。

>>> s = 'hello'
>>> t1 = s
>>> t2 = s[:]
>>> print s, t1, t2
hello hello hello
>>> s = 'good bye'
>>> print s, t1, t2
good bye hello hello

但是:

>>> li1 = [1,2]
>>> li = [1,2]
>>> li1 = li
>>> li2 = li[:]
>>> print li, li1, li2
[1, 2] [1, 2] [1, 2]
>>> li[0] = 0
>>> print li, li1, li2
[0, 2] [0, 2] [1, 2]

那么为什么在处理字符串时使用它呢? 内置字符串是不可变的,但是每当您编写一个期望字符串的库函数时,用户可能会给您一些“看起来像字符串”的东西"和 "表现得像一个字符串",但是是一个自定义类型。这种类型可能是可变的,因此最好注意这一点。

这样的类型可能看起来像:

class MutableString(object):
def __init__(self, s):
self._characters = [c for c in s]

def __str__(self):
return "".join(self._characters)

def __repr__(self):
return "MutableString(\"%s\")" % str(self)

def __getattr__(self, name):
return str(self).__getattribute__(name)

def __len__(self):
return len(self._characters)

def __getitem__(self, index):
return self._characters[index]

def __setitem__(self, index, value):
self._characters[index] = value

def __getslice__(self, start, end=-1, stride=1):
return str(self)[start:end:stride]


if __name__ == "__main__":
m = MutableString("Hello")
print m
print len(m)
print m.find("o")
print m.find("x")
print m.replace("e", "a") #translate to german ;-)
print m
print m[3]
m[1] = "a"
print m
print m[:]

copy1 = m
copy2 = m[:]
print m, copy1, copy2
m[1] = "X"
print m, copy1, copy2

免责声明:这只是一个示例,用于展示其工作原理并鼓励使用 [:]。它未经测试、不完整且性能可能非常糟糕

关于Python 你为什么要使用 [ :] over =,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14433759/

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