循序渐进PYTHON3(二) -- 数据类型

数据类型

一、数字(int)

  Python可以处理任意大小的正负整数,但是实际中跟我们计算机的内存有关,在32位机器上,整数的位数为32位,取值范围为 -2**31~2**31-1,在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1。对于int类型,需要掌握的方法不多,看 下面的几个例子:

1
2
3
4
5
6
a=4
print(a.bit_length()) # 4在二进制中可以用最少3位 100 来表示4,所以输出3
print(int('4'))       #将字符串4转换成整数4
 
# int还可下面的将二进制的字符串转换成整数, base=2 代表前面的字符串是二进制。
print(int('1010',base=2)) # 输出10

二、字符串(str)

  字符串的常用功能很多,下面就列举一下:

capitalize # 如果字符串中的第一个字符是字母,将其变为大写,其余字母变为小写

1
2
3
4
5
6
7
>>> a = '123,HELLO,world!'
>>> a.capitalize()
'123,hello,world!'
 
>>> a = 'hELLO,World!'
>>> a.capitalize()
'Hello,world!'

 casefold # 将字符串中的大写变成小写,和lower 类似。casefold对其他语言更有效。

                 总结来说,汉语 & 英语环境下面,继续用 lower()没问题;要处理其它语言且存在大小写情况的时候再用casefold() 

1
2
3
4
5
6
7
8
9
10
>>> a = 'hELLO,World!'
>>> print(a.casefold())
hello,world!
>>>
 
s = 'ß' #德语
a=s.lower() #  'ß'
b=s.casefold() # 'ss'
print(a,b)
ß ss

 center(self, width, fillchar=None) # 把字符串居中,两边补齐fillchar,最终字符串总长度为width

 
1
2
3
>>> a = 'li'
>>> print(a.center(40,'-'))
-------------------li-------------------

 count(self, sub, start=None, end=None) # 查看子字符串在字符串中的数量

 

1
2
3
4
5
6
7
8
9
>>> a = 'my name is han meimei'
>>> print(a.count(' '))
4
>>> print(a.count(' ',3,8))
1
>>> print(a.count('m',3,8))
1
>>> print(a.count('m'))
4

 

 endode #

pass

endswith(self, suffix, start=None, end=None)  # 查看字符串从start位置到end位置这一段的结尾是不是suffix

 

1
2
3
4
5
6
7
8
9
10
11
12
>>> a = 'my name is han meimei'
>>> b = a.endswith('meimei')
>>> print(b)
True
>>> if a.endswith('meimei'):
...   print('你好')
...
你好
>>> print(a.endswith('is',3,9))
False
>>> print(a.endswith('is',3,10)) #顾头不顾尾原则
True

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def capitalize(self): # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str
         
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""
 
    def casefold(self): # real signature unknown; restored from __doc__
        """
        S.casefold() -> str
         
        Return a version of S suitable for caseless comparisons.
        """
        return ""
 
    def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str
         
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""
 
    def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int
         
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0
 
    def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes
         
        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""
 
    def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool
         
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False
 
    def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str
         
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""
 
    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int
         
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
         
        Return -1 on failure.
        """
        return 0
 
    def format(*args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str
         
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass
 
    def format_map(self, mapping): # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str
         
        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""
 
    def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int
         
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0
 
    def isalnum(self): # real signature unknown; restored from __doc__
        """
        S.isalnum() -> bool
         
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False
 
    def isalpha(self): # real signature unknown; restored from __doc__
        """
        S.isalpha() -> bool
         
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False
 
    def isdecimal(self): # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool
         
        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False
 
    def isdigit(self): # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool
         
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False
 
    def isidentifier(self): # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool
         
        Return True if S is a valid identifier according
        to the language definition.
         
        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False
 
    def islower(self): # real signature unknown; restored from __doc__
        """
        S.islower() -> bool
         
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False
 
    def isnumeric(self): # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool
         
        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False
 
    def isprintable(self): # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool
         
        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False
 
    def isspace(self): # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool
         
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False
 
    def istitle(self): # real signature unknown; restored from __doc__
        """
        S.istitle() -> bool
         
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False
 
    def isupper(self): # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool
         
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False
 
    def join(self, iterable): # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str
         
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""
 
    def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str
         
        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""
 
    def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str
         
        Return a copy of the string S converted to lowercase.
        """
        return ""
 
    def lstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str
         
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
 
    def maketrans(self, *args, **kwargs): # real signature unknown
        """
        Return a translation table usable for str.translate().
         
        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass
 
    def partition(self, sep): # real signature unknown; restored from __doc__
        """
        S.partition(sep) -> (head, sep, tail)
         
        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass
 
    def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str
         
        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""
 
    def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int
         
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
         
        Return -1 on failure.
        """
        return 0
 
    def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int
         
        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0
 
    def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str
         
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""
 
    def rpartition(self, sep): # real signature unknown; restored from __doc__
        """
        S.rpartition(sep) -> (head, sep, tail)
         
        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass
 
    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings
         
        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return []
 
    def rstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.rstrip([chars]) -> str
         
        Return a copy of the string S with trailing whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
 
    def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings
         
        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []
 
    def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings
         
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []
 
    def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool
         
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False
 
    def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str
         
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
 
    def swapcase(self): # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str
         
        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""
 
    def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str
         
        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""
 
    def translate(self, table): # real signature unknown; restored from __doc__
        """
        S.translate(table) -> str
         
        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""
 
    def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str
         
        Return a copy of S converted to uppercase.
        """
        return ""
 
    def zfill(self, width): # real signature unknown; restored from __doc__
        """
        S.zfill(width) -> str
         
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""

  

 

 三、列表(list)

  列表是Python内置的一种数据类型是列表,是一种有序的集合,可以随时添加和删除其中的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
l=['a','b','cc',4]     #定义一个列表
 
l.insert(4,6)               #在下标为4的位置,插入值6
 
l.append(5)         #添加一个元素,l=['a', 'b', 'cc', 4, 5]
 
l.pop()           #从尾部删除一个元素,l=['a', 'b', 'cc', 4]
 
l.remove('a')         #从列表中移除 'a',l=['b', 'cc', 4]
 
l.extend(['gg','kk'])     #添加一个列表['gg','kk'], l=['b', 'cc', 4, 'gg', 'kk']
 
l.reverse()          #反转一个列表,l=['kk', 'gg', 4, 'cc', 'b']
 
print(l.count('kk'))     #某元素出现的次数 输出 1
 
print(l.index('gg'))     #元素出现的位置,输出 1
 
for i in l:          #循环输出列表元素
    print(i)
 
print(l[0:4:2])       #列表切片,以步长2递增,输出['kk', 4]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def append(self, p_object): # real signature unknown; restored from __doc__
    """ L.append(object) -> None -- append object to end """
    pass
 
def clear(self): # real signature unknown; restored from __doc__
    """ L.clear() -> None -- remove all items from L """
    pass
 
def copy(self): # real signature unknown; restored from __doc__
    """ L.copy() -> list -- a shallow copy of L """
    return []
 
def count(self, value): # real signature unknown; restored from __doc__
    """ L.count(value) -> integer -- return number of occurrences of value """
    return 0
 
def extend(self, iterable): # real signature unknown; restored from __doc__
    """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
    pass
 
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
    """
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.
    """
    return 0
 
def insert(self, index, p_object): # real signature unknown; restored from __doc__
    """ L.insert(index, object) -- insert object before index """
    pass
 
def pop(self, index=None): # real signature unknown; restored from __doc__
    """
    L.pop([index]) -> item -- remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.
    """
    pass
 
def remove(self, value): # real signature unknown; restored from __doc__
    """
    L.remove(value) -> None -- remove first occurrence of value.
    Raises ValueError if the value is not present.
    """
    pass
 
def reverse(self): # real signature unknown; restored from __doc__
    """ L.reverse() -- reverse *IN PLACE* """
    pass
 
def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
    """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
    pass

  

四、元组(tuple)

  tuple和list非常类似,但是tuple一旦初始化就不能修改,tuple也是有序的,tuple使用的是小括号标识。

1
2
3
4
5
6
7
8
9
10
11
12
t=('a','b','b','c')   #定义一个元组
 
print(t.index('b'))   #索引出元素第一次出现的位置,还可以指定在某一范围里查找,这里默认在整个元组里查找输出1
 
print(t.count('b'))   #计算元素出现的次数,这里输出2
 
print(len(t))      #输出远组的长度,这里输出4
 
for i in t:
    print(i)       #循环打印出元组数据
 
print(t[1:3])       #切片 输出('b','b')
1
2
3
4
5
6
7
8
9
10
def count(self, value): # real signature unknown; restored from __doc__
     """ T.count(value) -> integer -- return number of occurrences of value """
     return 0
 
 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
     """
     T.index(value, [start, [stop]]) -> integer -- return first index of value.
     Raises ValueError if the value is not present.
     """
     return 0

  

五、字典(dict)

  字典是无序的,使用键-值(key-value)存储,具有极快的查找速度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
 
d.get('Bob')                     #根据key获取values,如果不存在返回None,这里输出75
 
d.pop('Bob')                     #根据键删除某一元素 d={'Michael': 95, 'Tracy': 85}
 
d['Jason']=99                       #新增元素 d={'Michael': 95, 'Tracy': 85, 'Jason': 99}
 
d.setdefault('Age', 'xx')                          #setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。
 
d.fromkeys()                                         #可能有问题           
 
d.update()                                            #update() 函数把字典dict2的键/值对更新到dict里。dict里没有的就直接添加                              
 
print(len(d))                       #输出字典长度,这里输出3
 
print('Jason' in d)                 #python3 中移除了 has_key,要判断键是否存在用in
 
for i in d:
    print(i)                     #循环默认按键输出
 
for i in d.values():                #循环按值输出
    print(i)
 
for k,v in d.items():                #循环按键值输出
    print(k,v)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def clear(self): # real signature unknown; restored from __doc__
     """ D.clear() -> None.  Remove all items from D. """
     pass
 
 def copy(self): # real signature unknown; restored from __doc__
     """ D.copy() -> a shallow copy of D """
     pass
 
 @staticmethod # known case
 def fromkeys(*args, **kwargs): # real signature unknown
     """ Returns a new dict with keys from iterable and values equal to value. """
     pass
 
 def get(self, k, d=None): # real signature unknown; restored from __doc__
     """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
     pass
 
 def items(self): # real signature unknown; restored from __doc__
     """ D.items() -> a set-like object providing a view on D's items """
     pass
 
 def keys(self): # real signature unknown; restored from __doc__
     """ D.keys() -> a set-like object providing a view on D's keys """
     pass
 
 def pop(self, k, d=None): # real signature unknown; restored from __doc__
     """
     D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
     If key is not found, d is returned if given, otherwise KeyError is raised
     """
     pass
 
 def popitem(self): # real signature unknown; restored from __doc__
     """
     D.popitem() -> (k, v), remove and return some (key, value) pair as a
     2-tuple; but raise KeyError if D is empty.
     """
     pass
 
 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
     """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
     pass
 
 def update(self, E=None, **F): # known special case of dict.update
     """
     D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
     If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
     If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
     In either case, this is followed by: for k in F:  D[k] = F[k]
     """
     pass
 
 def values(self): # real signature unknown; restored from __doc__
     """ D.values() -> an object providing a view on D's values """
     pass

  

 补充

深浅copy

为什么要拷贝?

1
当进行修改时,想要保留原来的数据和修改后的数据

数字字符串 和 集合 在修改时的差异?(深浅拷贝不同的终极原因)

1
2
3
在修改数据时:
  数字字符串:在内存中新建一份数据
         集合:修改内存中的同一份数据

对于集合,如何保留其修改前和修改后的数据?

1
在内存中拷贝一份

对于集合,如何拷贝其n层元素同时拷贝?

1
深拷贝
复制代码
复制代码
 1 浅copy
 2 >>> dict = {"a":("apple",),"bo":{"b":"banna","o":"orange"},"g":["grape","grapefruit"]}
 3 >>> dict = {"a":("apple",),"bo":{"b":"banna","o":"orange"},"g":["grape","grapefruit"]}
 4 >>> dict2 = dict.copy()
 5 
 6 
 7 >>> dict["g"][0] = "shuaige"  #第一次我修改的是第二层的数据
 8 >>> print dict
 9 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']}
10 >>> print dict2
11 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']}
12 >>> id(dict["g"][0]),id(dict2["g"][0])
13 (140422980581296, 140422980581296)  #从这里可以看出第二层他们是用的内存地址
14 >>>
15 
16 
17 >>> dict["a"] = "dashuaige"  #注意第二次这里修改的是第一层
18 >>> print dict
19 {'a': 'dashuaige', 'bo': {'b': 'banna', 'o': 'orange'}, 'g':['shuaige','grapefruit']}'g': ['shuaige', 'grapefruit']}'g': ['shuaige', 'grapefruit']}'g': ['shuaige', 'grapefruit']}
20 >>> print dict2 21 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']} 22 >>> 23 >>> id(dict["a"]),id(dict2["a"]) 24 (140422980580816, 140422980552272) #从这里看到第一层他们修改后就不会是相同的内存地址了! 25 >>> 26 27 28 #这里看下,第一次我修改了dict的第二层的数据,dict2也跟着改变了,但是我第二次我修改了dict第一层的数据dict2没有修改。 29 说明:浅copy只是第一层是独立的,其他层面是公用的!作用节省内存 30 31 深copy 32 33 >>> import copy #深copy需要导入模块 34 >>> dict = {"a":("apple",),"bo":{"b":"banna","o":"orange"},"g":["grape","grapefruit"]} 35 >>> dict2 = copy.deepcopy(dict) 36 >>> print dict 37 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']} 38 >>> print dict2 39 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']} 40 >>> dict["g"][0] = "shuaige" #修改第二层数据 41 >>> print dict
42 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']}
43 >>> print dict2
44 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']}
45 >>> id(dict["g"][0]),id(dict2["g"][0])
46 (140422980580816, 140422980580288)  #从这里看到第二个数据现在也不是公用了
47 
48 # 通过这里可以看出他们现在是一个完全独立的,当你修改dict时dict2是不会改变的因为是两个独立的字典!

'g': ['shuaige', 'grapefruit']} 20 >>> print dict2 21 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']} 22 >>> 23 >>> id(dict["a"]),id(dict2["a"]) 24 (140422980580816, 140422980552272) #从这里看到第一层他们修改后就不会是相同的内存地址了! 25 >>> 26 27 28 #这里看下,第一次我修改了dict的第二层的数据,dict2也跟着改变了,但是我第二次我修改了dict第一层的数据dict2没有修改。 29 说明:浅copy只是第一层是独立的,其他层面是公用的!作用节省内存 30 31 深copy 32 33 >>> import copy #深copy需要导入模块 34 >>> dict = {"a":("apple",),"bo":{"b":"banna","o":"orange"},"g":["grape","grapefruit"]} 35 >>> dict2 = copy.deepcopy(dict) 36 >>> print dict 37 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']} 38 >>> print dict2 39 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']} 40 >>> dict["g"][0] = "shuaige" #修改第二层数据 41 >>> print dict 42 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['shuaige', 'grapefruit']} 43 >>> print dict2 44 {'a': ('apple',), 'bo': {'b': 'banna', 'o': 'orange'}, 'g': ['grape', 'grapefruit']} 45 >>> id(dict["g"][0]),id(dict2["g"][0]) 46 (140422980580816, 140422980580288) #从这里看到第二个数据现在也不是公用了 47 48 # 通过这里可以看出他们现在是一个完全独立的,当你修改dict时dict2是不会改变的因为是两个独立的字典!
复制代码
复制代码
posted @ 2017-11-28 19:46  北方客888  阅读(153)  评论(0编辑  收藏  举报