aggregate (set) Is an unordered sequence of non-repeating elements .1,2,3,4,1,2,3 = 1,2,3,4
1). Use braces { } perhaps set() Function to create a collection ;
2). Be careful :
To create an empty collection, you must use the set() instead of { }
{ } Is used to create an empty dictionary .
# 1. Set creation
s = {1, 2, 3, 1, 2, 3} # {1, 2, 3}
print(s, type(s))
## Be careful 1: The elements of a collection must have immutable data types .
# s = {1, 2, 3, [1, 2, 3]}
# print(s, type(s))
## Be careful 2: Empty collection cannot be used {}, And you want to use set()
# s = {}
# print(s, type(s)) ##{} <class 'dict'>
s = set()
print(s, type(s))
A set is an unordered, non repeating sequence of elements . So connection operation 、 Repeat 、 Indexes 、 Slicing doesn't work for him .
# I won't support it +,*, index, slice( Because the set is out of order and does not repeat )
# Support in and not in
print(1 in {1, 2, 3, 4})
# 4-1). increase
# add: Add a single element
# update: Add multiple elements
s = {1, 2, 3}
s.add(100)
print(s)
s = {1, 2, 3}
s.update({4, 5, 6})
print(s)
# remove: If the element exists , Delete , Otherwise, the report will be wrong
# discard: If the element exists , Delete , otherwise do nothing
# pop: Randomly delete an element
# Remove elements , If the collection is empty, an error is reported
s = {1, 2, 3}
s.remove(3)
print(s)
s = {1, 2, 3}
s.discard(100)
print(s)
s = {1, 66, 2,99, 78, 3}
s.pop()
print(s)
# 3-3). see
# Difference set : s1 - s2
# intersection : s1 & s2
# Symmetric difference : s1 ^ s2
# Combine : s1 | s2
s1 = {1, 2, 3}
s2 = {1, 2}
print(s1 - s2) # {3}
print(s1 & s2) # {1, 2}
s1 = {1, 2, 3}
s2 = {1, 2, 4}
print(s1 ^ s2) # {3, 4}, {1, 2, 3, 4} - {1, 2} = {3,4}
print(s1 | s2) # {1, 2, 3, 4}
print(s1.issubset(s2)) # False
print(s1.isdisjoint(s2)) # False
Be careful :
issubset() Method is used to determine whether all elements of the collection are included in the specified collection , If so, return True, Otherwise return to False.
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z) ##True
isdisjoint() Method is used to determine whether two sets contain the same element , If there is no return True, Otherwise return to False..
s1 = {1, 3}
s2 = {1, 2, 3}
print(s1.isdisjoint(s2)) ### False
## You can copy But we can't add, delete or change
s = frozenset({1, 2, 3})
print(s, type(s))
Random generation N A digital (1 To 1000 Between ), And in order from large to small :
import random
N = int(input(" Please enter N:"))
s = set()
print(s,type(s))
for i in range(N):
num = random.randint(1,1000)
s.add(num)
print(sorted(s,reverse=True))
Dictionary is another variable container model , And can store any type of object .
Keys are usually the only , If you repeat the last key value pair, the previous one will be replaced , Value doesn't need to be unique .
# key-value Right or key value right
d = {"name":"westos", "age":18, "city":" Xi'an "}
print(d, type(d))
d = {}
print(d, type(d))
Output :
{'name': 'westos', 'age': 18, 'city': ' Xi'an '} <class 'dict'>
{} <class 'dict'>
I won't support it +,*, index, slice( Because the set is out of order and does not repeat )
Support in and not in
d = {“name”:“westos”, “age”:18, “city”:“ Xi'an ”}
print(‘name’ in d) # True, Judge whether it is all key Worthy member
print(“westos” in d) # False
"""
View all : keys, values, items
view local : d[key], d.get(key), d.get(key, default-value)
"""
d = {"name":"westos", "age":18, "city":" Xi'an "}
print(d.keys()) # Look at all the words in the dictionary key value
print(d.values()) # Look at all the words in the dictionary value value
print(d.items()) # Look at all the words in the dictionary key-value value (item Elements )
print(d['name']) # see key by name Corresponding value value
# print(d['province']) # see key Corresponding vlaue value , If there is no error .
print(d.get('province')) # see key Corresponding vlaue value , Return if present , If not, return None.
print(d.get('province', " shaanxi ")) # see key Corresponding vlaue value , Return if present , If not, the default value is returned .
d = {"name":"westos", "age":18}
d['city'] = " Xi'an " # key Add... If it doesn't exist
print(d)
d['city'] = " Beijing " # key Modification of existence value value
print(d)
d = {"name":"westos", "age":18}
d.setdefault('city', " Xi'an ") # key Add... If it doesn't exist
print(d)
d.setdefault('city', " Beijing ") # key There is , be do nothing
print(d)
d = {"name":"westos", "age":18}
d.pop('name')
print(d) ##{'age': 18}
d = {"name":"westos", "age":18}
del d['name']
print(d) ##{'age': 18}
d = {"name":"westos", "age":18, "city":" Xi'an "}
## By default , The dictionary will only traverse key value
for item in d:
print(item)
# If you traverse the dictionary key and value Well ?( Especially important )
for key,value in d.items(): # [('name', 'westos'), ('age', 18), ('city', ' Xi'an ')]
print(f"key={key}, value={value}")
# Default dictionary , set default value
# Default dictionary , set default value
d = defaultdict(int)
d['views'] += 1
d['transfer'] += 1
print(d)
#
d = defaultdict(list)
d['allow_users'].append('westos')
d['deny_users'].extend(['user1', 'user2'])
print(d)
d = defaultdict(set)
d['love_movies'].add(" The matrix ")
d['dislike_movies'].update({' The former 3', ' The movie xxxx'})
print(d)
Output is as follows :
defaultdict(<class 'int'>, {'views': 1, 'transfer': 1})
defaultdict(<class 'list'>, {'allow_users': ['westos'], 'deny_users': ['user1', 'user2']})
defaultdict(<class 'set'>, {'love_movies': {' The matrix '}, 'dislike_movies': {' The former 3', ' The movie xxxx'}})
practice :
defaultDict Let's do an exercise , hold list( Random generation 50 individual 1-100 Random number between ) Greater than 66 Elements of and less than 66 The elements of
from collections import defaultdict
import random
d = defaultdict(list)
num = []
for count in range(50):
num.append(random.randint(1,100))
for i in num:
if i > 66:
d[' Greater than 66 The elements of '].append(i)
else:
d[' Less than 66 The elements of '].append(i)
print(d)
Variable data type : You can add, delete, or modify . Variable data type , Allow the value of the variable to change , That is to say, if we do append、+= After this operation , Just changed the value of the variable , Instead of creating a new object , The address of the object referenced by the variable does not change , But for different objects with the same value , In memory, there are different objects , That is, each object has its own address , It's equivalent to saving multiple copies of the same value objects in memory , There is no reference count , It's a real object .
Immutable data types : You can't add, delete or change .python Immutable data types in , The value of a variable is not allowed to change , If you change the value of a variable , So I created a new object , And for objects of the same value , There is only one object in memory , There will be a reference count inside to record how many variables refer to the object .
Sequence :
圖像直方圖,In essence, it is to cou