Tuples. Dictionaries. Collections and built-in methods

Keywords: PHP hive REST Python Linux

- Restore content to start ---

1: tuple:

Similar to lists, you can store multiple values, multiple data types, but the difference is that the ancestor itself cannot be modified

1 Purpose: Record multiple values, tuples are more appropriate when multiple values have no changed requirements

2 Definition: Compared to the list type, just [] is replaced by () and multiple values of any type are separated by commas within ()

tile=(1,12,45,'kvein',[23,'hive'],'kill')#equivalence tile=tuple((1,12,45,'kvein',[23,'hive'])
tile=(1,12,45,'kvein',[23,'hive'],'kill')
print(type(tile))
>>><class 'tuple'>       When defining container types, even if there is only one element inside, you should also distinguish them by commas

2: Common Operations + Built-in Methods

Priority operations:

1. Value by index (forward + reverse): can only take, cannot save, cannot modify
 
tile=(1,12,45,'kvein',[23,'hive'],'kill')
print(tile[::2])     # Index and slice values are all set aside by step, defaulting from left to right
print(tile[::])

>>>(1, 45, [23, 'hive'])
>>>(1, 12, 45, 'kvein', [23, 'hive'], 'kill')

 

3. Length
 
tile=(1,12,45,'kvein',[23,'hive'],'kill')
print(len(tile))  # Number of elements in tuple
>>6

 

4. Member operation in and not in
tile=(1,12,45,'kvein',[23,'hive'],'kill')
k='kvein'
k in tile
print(k in tile)  # The member operation determines whether it is true or not and returns Ture or False
W='music'
W not in tile
print(W)


>>True 
>>music     #  none Returns a value when 

 

5. Cycle
tile=(1,12,45,'kvein',[23,'hive'],'kill')
for 1 in tile:

>>1,12,45,'kvein',[23,'hive'],'kill

print(t.count('a'))
 print(t.index('xxx'))

print(t.count('a'))   #Statistics'a'Number of occurrences in tuples

 print(t.index('xxx'))  # Index, Find

Summary: Multiple values can be stored
Ordered
* Invariant

2: List Type

Multiple values can be stored
Ordered
Variable

One: Basic Use
1 Purpose: Store multiple values, accessible by index
2 Definition: Separate multiple values of any type with commas within []
l=['egon','lxx','yxx'] # l=list(['egon','lxx','yxx'])
l1=list('hello') #list Is equivalent to calling a for Loop out in turn'hello'Put values in the list
print(l1)
l2=list({'x':1,'y':2,'z':3})
print(l2)
list(10000) # Report errors

3 Common actions + built-in methods

Priority operations:
#1,Access Values by Index(Forward Access+Reverse Access): Save or take
l=['egon','lxx','yxx']
print(l[0])
l[0]='EGON'
print(l)
print(l[-1])
print(l[3])
l[0]='EGON'  # Value can only be changed based on an existing index
l[3]='xxxxxxxx'  #If there is no direct error in the index

2. Slices (regardless of end, step length)

l=['egon','lxx','yxx',444,555,66666]
print(l[0:5])
print(l[0:5:2])   # Value the step regardless of the end
print(l[::-1])

3. Length len

l=['egon','lxx','yxx',444,555,66666,[1,2,3]]
print(len(l))

4. Member operation in and not in

l=['egon','lxx','yxx',444,555,66666,[1,2,3]]
print('lxx' in l)
print(444 in l)

5. Addition

l=['egon','lxx','y']
l.append('Just try')
l.append('The rest to God')
print(l)

>>['egon', 'lxx', 'y', 'Just try', 'The rest to God']

6. Insert a value before the specified index

l=['egon','lxx','yxx']
l.insert(0,'Don't pretend to be hard')
print(l)
l.insert(2,'The result won't play with you')
print(l)

7. Adding multiple elements at once

l = ['jason','nick']
l.extend(['tank','sean'])

8. Delete
l=['egon','lxx','yxx']

#Simple delete value:
#Mode 1:
del l[1] #Universal
print(l)
#Mode 2:
res=l.remove('lxx') #Specifies the value to delete, returns None
print(l,res)
9. Take a value from the list
l=['sdg',34,'Providence','Man-made']
res=l.pop(-1) # Delete values by index(Delete from the end by default),Returns the deleted value
print(l)
print(res)

>>['sdg', 34, 'Providence']
>>Man-made

8. Cycle

l=['egon','lxx','yxx']
for item in l:
    print(item)
>>egon
>>lxx
>>yxx
What you need to know
l=['egon','egon','lxx','yxx',444,555,66666]
print(l.count('egon'))
print(l.index('egon'))
print(l.index('yxx',0,1))
l.clear()
items=['a','b','c']
items='hello'
for item in items:
    l.append(item)
l.extend(items)
print(l)
l=['egon','egon','lxx','yxx',444,555,66666]
l.reverse()
print(l)
nums=[3,-1,9,8,11]
nums.sort(reverse=True)
print(nums)items=[1,'a','b',2items.sort()
 
10. Queue: FIFO
l=[]
# # Entry
l.append('first')
l.append('second')
l.append('third')
print(l)
 # # Queue
print(l.pop(0))
print(l.pop(0))
print(l.pop(0))
# Stack: FIFO
l=[]
# Push
l.append('first')
l.append('second')
l.append('third')
print(l)
# Stack Out
print(l.pop())
print(l.pop())
print(l.pop())

3. Dictionaries dict

Function: Can store multiple groups key:value Key-Value Pairs  key Yes value Description  key Typically, they are strings
  Actually this key Can only be an immutable type,value Can be of any data type

Definition:
# d = {'name':'jason','password':123}  # d = dict( {'name':'jason','password':123})
d2 = {'name':'jason','name':'tank','name':'nick','password':123}
print(type(d2))  #Print d2 Number type
print(len(d2))  # Print d2 Length
print(d2['name'])  
    #Press key Key-value pairs are one-to-one, key Cannot repeat assignment key If it repeats in a dictionary, only the most    The latter value
Assignment statement A new key-value pair is automatically added when the key does not exist

 4,delete
d3= {'name':'jason','password':'123'} del d3['name'] print(d3) res = d3.pop('name') # Pop-up is just value res = d3.pop('age') # Direct error when key does not exist print(res) print(d3)

5. get() gets value from key

d1 = {'name':'jason','pwd':123}
# print(d1['name'])
# print(d1['age'])
# print(d1.get('name','You gave it to me name In the dictionary key in'))
# res = d1.get('age')  # When Dictionary's key Non-existent returns without error None
# res1 = d1.get('xxx','You gave it to me age In the dictionary key in')  # Returns None without error when the key of the dictionary does not exist

 

 dict.fromkeys()  Create a dictionary quickly
l1 = ['name','password','age','hobby']
 print(dict.fromkeys(l1,123))


 dict.popitem()
 print(d1.popitem())  # Tail pops up key-value pairs as tuples

 dict.setdefault()
 d1 = {'name':'jason','pwd':123}
 res1 = d1.setdefault('name','xxoo')  # If the key exists, the value will not be modified and the original value will be changed key The corresponding value is returned to you
 print(d1,res1)
 res2 = d1.setdefault('age',18)  # Add a new key-value pair when the key does not exist and return the value of the new key-value pair to you
 print(d1,res2)

 dict.update()
 d1 = {'name':'jason','pwd':123}
 d2 = {"age":18}
  d1.update(d2)
 d1['age'] = 18
 d1.update(age=666)
 print(d1)


6,loop
 d1 = {'name':'jason','password':123}
 for i in d1:
     print(i)



"""
//Store multiple values
//disorder
//variable

4. Collection set

pythons=['Li Eryao','Zhang Jin Egg','Li Yin Bounce','Zhao Tong Egg','Zhang Tin Egg','alex','oldboy']
linuxs=['lxx','egon','Zhang Jin Egg','Zhang Tin Egg','alex','May Fourth leader']

l=[]
for stu in pythons:
    if stu in linuxs:
        l.append(stu)
print(l)

1: Basic use:set
1 Purpose: Relational operations, weight removal
2 Definition: Multiple values separated by commas within {}
The three main characteristics of a set:
2.1 Each value must be of an immutable type
2.2 Element cannot be repeated
Disordered elements in 2.3 set

s={1,3.1,'aa',(1,23),} # s=set({1,3.1,'aa',(1,23),})
print(s,type(s))

s={1,1,1,1,1,1,1,1,1,2,3}
print(s)

s={'a','b','c'}
s[0]

s=set('hello')
print(s)
print(set(['a','b','c',[1,2]])
# 3 Common operations+Built-in methods
pythons={'Li Eryao','Zhang Jin Egg','Li Yin Bounce','Zhao Tong Egg','Zhang Tin Egg','alex','oldboy'}
linuxs={'lxx','egon','Zhang Jin Egg','Zhang Tin Egg','alex','May Fourth leader'}
# Get and sign up python Course Enrollment linux Student in the course:intersection
print(pythons & linuxs)
print(pythons.intersection(linuxs))

# Get all the students who sign up for the Old Boy course:Union
print(pythons | linuxs)
print(pythons.union(linuxs))

# Enrollment Only python Student in the course: Difference set
print(pythons - linuxs)
print(pythons.difference(linuxs))

# Enrollment Only linux Student in the course: Difference set
print(linuxs - pythons)
print(linuxs.difference(pythons))

# Take students who have not enrolled in both courses at the same time:Symmetric difference set
print(pythons ^ linuxs)
print(pythons.symmetric_difference(linuxs))

# Is it equal
s1={1,2,3}
s2={3,1,2}
print(s1 == s2)

# Parent Set:A set is one that contains another set
s1={1,2,3}
s2={1,2}
print(s1 >= s2)
print(s1.issuperset(s2))

s1={1,2,3}
s2={1,2,4}
print(s1 >= s2)

# subset
s1={1,2,3}
s2={1,2}
print(s2 <= s1)
print(s2.issubset(s1))





# Operation required s1={1,2,3} s1.update({3,4,5}) print(s1) s1={1,2,3} res=s1.pop() print(res) s1={1,2,3} res=s1.remove(3) #Simple Delete,Return value is None print(s1) s1={1,2,3} s1.add(4) print(s1) s1={1,2,3} s2={1,2} s1.difference_update(s2) #s1=s1.difference(s2) print(s1) s1={1,2,3} res=s1.discard(3) ##Simple deletion, return value is None print(s1) print(res) s1.remove(444444) #Error if deleted element does not exist s1.discard(444444) #Deleted element does not exist without error s1={1,2,3} s2={1,2,4} print(s1.isdisjoint(s2)) #Return if two sets do not intersect True s1={1,2,3} s2={4,5,6} print(s1.isdisjoint(s2)) #Return if two sets do not intersect True #2. Summary of this type # 1 Store multiple values # # 2 disorder # # 3 set variable s={1,2,3} print(id(s)) s.add(4) print(id(s)) # Collection Weighting # Limitations #1,The order of the original data types cannot be guaranteed #2,A set can be used to weight multiple values contained in a data when they are all of an immutable type names=['alex','egon','alex','alex','egon','lxx'] s=set(names) print(s) l=list(s) print(l) stus_info=[ {'name':'egon','age':18}, {'name':'alex','age':73}, {'name':'oldboy','age':84}, {'name': 'egon', 'age': 18}, {'name': 'egon', 'age': 18}, {'name': 'egon', 'age': 18}, {'name': 'oldboy', 'age': 84}, ] # set(stus_info) # Report errors l=[] for info in stus_info: if info not in l: l.append(info) # print(l) stus_info=l print(stus_info)

 

 

 
 
 
 
 

 

 

 

Posted by mjm on Thu, 04 Jul 2019 10:24:24 -0700