程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python -- collections and dictionaries

編輯:Python

One 、 aggregate ( A mountain cannot be a collection of two tigers )

1. Definition of set

aggregate (set) Is an unordered sequence of non-repeating elements .1,2,3,4,1,2,3 = 1,2,3,4

2. Set creation :

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))

3. The properties of sets

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. Operations on collections

1. increase

# 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)

2. Delete

# 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. see

# 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

4. expand : frozenset Immutable set

## You can copy But we can't add, delete or change
s = frozenset({1, 2, 3})
print(s, type(s))

5. Set of exercise topics

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))

Two 、 Dictionaries

1. Dictionary definition

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 .

2. Dictionary creation

# 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'>

3. Dictionary features

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

4. Dictionary operation

4.1 see

"""
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 .

4.2 Add and modify

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)

4.3 Delete

d = {"name":"westos", "age":18}
d.pop('name')
print(d) ##{'age': 18}
d = {"name":"westos", "age":18}
del d['name']
print(d) ##{'age': 18}

4. Ergodic dictionary (for)

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}")

5.defaultdict

# 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)

3、 ... and 、 Summary of data types

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 .

  1. Variable and immutable
  • Variable data type : list, set, dict
  • Immutable data types : value type ,tuple, str

Sequence :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved