python whole stack development, Day7 (tuple conversion, as well as a list of dictionary pits, collection, relationship test, depth copy, encoding supplementary)

A tuple conversion 

digital

you = (1) 
tu1 = (1) 
print (you type (you)) 
print (tu1 type (tu1))

Perform output:

1 <class 'int'>
(1,) <class 'tuple'>

 

String

you = ( 'PDR') 
tu1 = ( 'PDR') 
print (you type (you)) 
print (tu1 type (tu1))

Perform output:

lao <class 'str'>
('lao',) <class 'tuple'>

 

List

tu = ([1,2,3]) 
tu1 = ([1,2,3]) 
print (you type (tu)) 
print (tu1 type (tu1))

Perform output:

[1, 2, 3] <class 'list'>
([1, 2, 3],) <class 'tuple'>

 

Summary:
For the tuple: If only one element, and there is no comma, this element will not change the data type.
If the end of the comma is the tuple type

 

Tuple into a list

tu = (1,2,3), 
the list = (tu) 
print (li)

Perform output:

[1, 2, 3]

 

Lists into tuples

tu = [1,2,3] 
li = tuple (that) 
print (li)

Perform output:

(1, 2, 3)

 

String is converted directly into a tuple no method.

Unless the string into a list, and then converted to a tuple

 

What numbers, strings, lists, tuples, dictionaries False Boolean values ​​corresponding respectively?

Digital 0

String '

List []

Tuple ()

dictionary{}

 

Second, the list of the pit

The index is an odd number of elements deleted

li = ['laonanhai','python','alex','wusir','egon','ritian','nvsheng']

Normal writing

li = ['laonanhai','python','alex','laonanhai','egon','ritian','nvsheng']
for i in li:
    if li.index(i) % 2 == 1:
        li.pop(li.index(i))
print(li)

Perform output:
[ 'laonanhai', 'Alex', 'laonanhai', 'ritian', 'nvsheng']

The resulting output is not what I want, how to do it? There are three kinds of writing

First, use the slice , the simplest

= Li [ 'laonanhai', 'Python', 'Alex', 'laonanhai', 'Egon', 'ritian', 'nvsheng'] 
del Li [. 1 :: 2] 
Print (Li)

Perform output:

[ 'Laonanhai', 'alex', 'Egon', 'nvsheng']

 

The second, covering the use of the new list

li = [ 'missing', 'python', 'stupid', 'missing', egon ', ritian', nvsheng ' 
li_1 = [] 
for i in range (len (li)): 
    if i% 2 == 0: 
        li_1.append (li [i]) 
 
li = li_1 
print (li)

Execution output, the effect ibid.

 

The third, reverse deleted.

li = [ 'missing', 'python', 'stupid', 'missing', egon ', ritian', nvsheng ' 
for i in range (len (li) -1, -1, -1): 
    if i% 2 == 1: 
        del li [i] 
 
print (li)

Execution output, the effect ibid.

Delete backwards, does not affect the front, only affects the back.

 

to sum up:

For the list, a list circulating at the time, it is best not to carry out the action (Once deleted, the index will change), error-prone deleted.

 

Third, the pit dictionary

Dictionary fromkeys () method for creating a new dictionary, and to iterables the elements are as dictionary keys and all the keys correspond to the same value, default None

dic = dict.fromkeys('abc','alex')
print(dic)

Perform output:

{'c': 'alex', 'b': 'alex', 'a': 'alex'}

 

Use the list to create a new dictionary

dic = dict.fromkeys([1,2,3],[])
print(dic)

Perform output:

{1: [], 2: [], 3: []}

 

The first pit dictionary

Add an element to the list 1

dic = dict.fromkeys([1,2,3],[])
dic[1].append('北京')
print(dic)

Perform output:

{1: [ 'Beijing'], 2: [ 'Beijing'] 3: [ 'Beijing']}

 

Pit came, these three lists, corresponding in memory is the same list

 

The second pit dictionary

The dictionary contains the key elements of K, corresponding to the key-value pair deletion

dic = {'k1':'value1','k2':'value2','name':'wusir'}

Normal idea of ​​writing:

dic = {'k1':'value1','k2':'value2','name':'wusir'}
for i in dic.keys():
    if 'k' in i:
        dic.pop(i)
         
print(dic)

Execution error:

RuntimeError: dictionary changed size during iteration

Means that, in the course of the cycle the dictionary, not allowed to change the dictionary

Put it another thought, most added in the dictionary

dic = {'k1':'value1','k2':'value2','name':'wusir'}
count = 0
for i in dic:
    dic[i+str(count)] = dic[i]
    count +=1
 
print(dic)

Execution error, the effect above.

 

This question should do so on the first key contains k, added to the list
and then circulating the list, delete the dictionary Key

dic = {'k1':'value1','k2':'value2','name':'wusir'}
li = []
for i in dic:
    if 'k' in i:
        li.append(i)
for i in li:
    dic.pop(i)
print(dic)

Perform output:

{'name': 'wusir'}

 

Summary:
In the cycle list or dictionary of the time, do not do to add or delete.

 

Fourth, the collection

Collection is not indexed, it is unordered.

type of data:

Not repeat, disorderly, it is elements inside the hash. It itself is not a hash, he can not serve as key dictionary

effect:

1. deduplication

2. The relationship between the test data

 

List deduplication

To the list of heavy, directly converted into a collection, it

li = [11,11,22,22,33,33,33,44] 
li = list (set (li)) 
print (li)

Perform output:

[33, 11, 44, 22]

 

A set of common operations

increase

add () adds an element

set1 = {'wusir','ritian'}
set1.add('女神')
print(set1)

Perform output:

{ 'Wusir', 'goddess', 'ritian'}

 

update () iteration increases

set1 = {'wusir','ritian'}
set1.update('abc')
print(set1)

Perform output:

{'wusir', 'c', 'ritian', 'b', 'a'}

 

delete

remove () removes an element

set1 = {'wusir','ritian'}
set1.remove('wusir')
print(set1)

Perform output:

{'ritian'}

 

pop () deletes random

pop () Returns the value is

set1 = {'wusir','ritian'}
print(set1.pop())
print(set1)

Perform output:

{'ritian'}

 

clear () empty set

set1 = {'wusir','ritian'}
set1.clear()
print(set1)

Perform output:

set()

 

del Delete Collection

set1 = {'wusir','ritian'}
del set1

 

Collection method is not changed

check

Check only for circulation

set1 = {'wusir','ritian'}
for i in set1:
    print(i)

Perform output:

ritian
wusir

 

Fifth, set relationship test

Intersection (& or intersection)

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 & set2)
print(set1.intersection(set2))

Perform output:

{4, 5}
{4, 5}

 

Union (| or union)

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 | set2)
print(set1.union(set2))

Perform output:

{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}

 

Anti intersection (^ or symmetric_difference)

And the intersection, take the opposite result, that is to say, the same removed, leaving different.

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 ^ set2)
print(set1.symmetric_difference(set2))

Perform output:

{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}

 

Set difference (- or difference)

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
print(set1 - set2)
print(set1.difference(set2))

Perform output:

{1, 2, 3}
{1, 2, 3}

 

Subset (issubset)

Determining whether the set is a collection comprising a further

set1 = {1,2,3}
set2 = {1,2,3,4,5,6}
print(set1.issubset(set2))

Perform output:

True

 

Superset (issuperset)

Further comprising determining whether a set of a set

set1 = {1,2,3}
set2 = {1,2,3,4,5,6}
print(set2.issuperset(set1))

Perform output:

True

 

Set relationship test, remember comply with it, the letters too long, difficult to remember.

frozenset () will be converted to a set of hash type , it can be used as a dictionary key

set1 = {'barry','wusir'}
set2 = frozenset(set1)
print(set2)

Perform output:

frozenset({'barry', 'wusir'})

 

Sixth, copy depth

li_1 = [1,2,3] 
li_2 = li_1 
li_2.append (456) 
print (li_1) 
print (li_2)

Perform output:

[1, 2, 3, 456]
[1, 2, 3, 456]

The results are the same.

For the assignment operator, pointing to the same memory address. Dictionaries, lists, sets are the same

 

copy

li_1 = [1,2,3] 
li_2 li_1.copy = () 
li_2.append (111) 
print (li_1) 
print (li_2)

Perform output:

[1, 2, 3]
[1, 2, 3, 111]

 

not point to a copy, it has opened up a memory space in memory

li_1 = [1,2,3] 
li_2 li_1.copy = () 
li_2.append (111) 
print (the (li_1)) 
print (the (li_2))

Perform output:

2204788806984
2204788808776

Found that memory address is not the same.

 

2 copy layer list

= Li_1 [1,2, [l, 2,3],. 4] 
Li2 = li_1.copy () 
# internal list to add a value 
Li_1 [2] .append (666) 
Print (Li_1) 
Print (Li2)

Perform output:

[1, 2, [1, 2, 3, 666], 4]
[1, 2, [1, 2, 3, 666], 4]

 

why? Because the internal memory address list is a separate, once modified, where other references, will take effect.

For shallow copy, the first layer of the new memory address created

The second layer from the start point to the same memory address is

copy rarely used, to interview examination.

 

Deep copy must import a copy module

Copy Import 
Li_1 = [1,2, [l, 2,3],. 4] 
Li2 = copy.deepcopy (Li_1) 
# internal list to add a value 
Li_1 [2] .append (666) 
Print (Li_1) 
Print (Li2)

Perform output:

[1, 2, [1, 2, 3, 666], 4]
[1, 2, [1, 2, 3], 4]

 

Deep copy, each layer is entirely new memory address

Copy shallow, the new first layer, the second layer begins, a common memory address

For deep copy, the two are completely separate, change any element of any one of (no matter how many layers), another absolutely does not change

 

Interview questions:

The following example, l2 is deep or shallow copy copy

l1 = [1,2,3,[22,33]]
l2 = l1[:]
l1[3].append(666)
print(l2)

Perform output:

[1, 2, 3, [22, 33, 666]]

 

For slice it, it belongs to the shallow copy

 

Seven coding supplement

= S 'Alex' 
S1 = s.encode ( 'UTF-. 8') #unicode ->. 8 encode UTF- 
s2 = s.encode ( 'gbk') #unicode -> gbk decoding 
# utf-8 converted to unicode 
s1.decode = S3 ( 'UTF-. 8') 
Print (S3)

Perform output:

alex

gbk utf-8 and can not be directly converted into each other
must can pass unicode.

s = 'old boys' 
S1 = s.encode ( 'GBK') is converted to #unicode GBK 
 
S2 = s1.decode ( 'GBK') #gbk converted to Unicode 
s2.encode ( 'UTF-. 8') is converted to #unicode . 8-UTF 
Print (S2)

Perform output:

old boys

Guess you like

Origin www.cnblogs.com/tu240302975/p/12651924.html