011、可变和不可变类型
本文最后更新于 67 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com

可变和不可变类型

列表是可变的(Mutable)

a = [1,2,3,4]
a
[1, 2, 3, 4]

通过索引改变:

a[0] = 100
a
[100, 2, 3, 4]

通过方法改变:

a.insert(3, 200)
a
[100, 2, 3, 200, 4]
a.sort()
a
[2, 3, 4, 100, 200]

字符串是不可变的(Immutable)

s = "hello world"
s
'hello world'

通过索引改变会报错:

s[0] = 'z'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in ()
----> 1 s[0] = 'z'

TypeError: 'str' object does not support item assignment

字符串方法只是返回一个新字符串,并不改变原来的值:

print s.replace('world', 'Mars')
print s
hello Mars
hello world

如果想改变字符串的值,可以用重新赋值的方法:

s = "hello world"
s = s.replace('world', 'Mars')
print s
hello Mars

或者用 bytearray 代替字符串:

s = bytearray('abcde')
s[1:3] = '12'
s
bytearray(b'a12de')

数据类型分类:

可变数据类型 不可变数据类型
list, dictionary, set, numpy array, user defined objects integer, float, long, complex, string, tuple, frozenset

字符串不可变的原因

其一,列表可以通过以下的方法改变,而字符串不支持这样的变化。

a = [1, 2, 3, 4]
b = a

此时, ab 指向同一块区域,改变 b 的值, a 也会同时改变:

b[0] = 100
a
[100, 2, 3, 4]

其二,是字符串与整数浮点数一样被认为是基本类型,而基本类型在Python中是不可变的。

谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇