current position:Home>How IOS developers learn Python Programming 8 - set type 3
How IOS developers learn Python Programming 8 - set type 3
2022-01-31 13:22:05 【Sissy's father】
This is my participation 11 Yue Gengwen challenges 8 God , Check out the activity details :2021 The last time Gengwen challenge .
Bytes
stay Python3
in the future , String and bytes
The types are completely separated :
character string
In order tocharacter
Is processed in units .bytes
The type is based onbyte
For units of .
bytes
Data types are basically the same as string data types in all operations and uses, even in built-in methods , It is also an immutable sequence object .
call bytes()
Generate bytes
example . For the same string, if different encoding methods are used to generate bytes
object , And you get different values :
>>> a = b'hello'
>>> type(a)
<class 'bytes'>
>>> b = bytes('hello',encoding='utf8')
>>> type(b)
<class 'bytes'>
Copy code
bytes
Type common conversion
- Byte to string
>>> d = b'world'
>>> d.decode()
'world'
>>> type(d)
<class 'bytes'>
Copy code
- String to byte
>>> e = 'world'
>>> e.encode()
b'world'
>>> type(e)
<class 'str'>
Copy code
aggregate set
set aggregate
: An unordered collection of non repeating elements , Basic functions include :
- Relationship testing
- Eliminate duplicate elements
set
Use braces {}
Framing elements , And separated by commas : ️ Be careful : If you want to create an empty collection , Must use set()
instead of {}
, Because the latter creates an empty dictionary .
>>> s = {1,2,3}
>>> s
{1, 2, 3}
>>> type(s)
<class 'set'>
>>> s = {} # Be careful , Empty {} Will default to dictionary
>>> type(s)
<class 'dict'>
>>> s = set() # Create an empty set ->new empty set object( Create an empty set )
>>> s
set()
>>> type(s)
<class 'set'>
>>> s = set([1,2,3,1,2,3,4]) # Create set , duplicate removal
>>> s
{1, 2, 3, 4}
>>> s1 = set("hello world") # Create set , duplicate removal
>>> s1
{'h', 'd', 'o', ' ', 'e', 'l', 'r', 'w'}
>>> s2 = set(123) # Be careful , Need to pass in iteratable objects , and int Type of 123 Not at all , So wrong reporting
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
Copy code
Set add elements
adopt add(key)
Method to add elements to set
in , Can be added repeatedly , But it won't work :
>>> s = set([1,2,3,1,2,3,4])
>>> s
{1, 2, 3, 4}
>>> s.add(3) # Add repeatedly , Automatic weight removal
>>> s
{1, 2, 3, 4}
>>> s.add(6) # Add success
>>> s
{1, 2, 3, 4, 6}
>>> s.add("cat") # Add success
>>> s
{1, 2, 3, 4, 6, 'cat'}
>>> s.add([1,2,3]) # Report errors , Like a dictionary Cannot add mutable objects
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Copy code
Collection Update
Can pass update()
Method , Update another object to the existing collection , This process will also be de duplicated :
>>> s = set([1,2,3,4,5])
>>> s.update("hello") # take hello Take it apart and put it into the collection
>>> s
{1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'}
>>> s.update("hello") # Still de weight
>>> s
{1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'}
Copy code
Remove elements
adopt remove(key)
Method deletes the specified element , Or use pop()
Method . Be careful , A collection of pop
Method cannot set parameters , Delete the specified element :
set.remove()
>>> s = {1, 2, 3, 4, 5, 'h', 'o', 'e', 'l'}
>>> s.remove(1) # Delete the element
>>> s
{2, 3, 4, 5, 'h', 'o', 'e', 'l'}
>>> s.remove('h') # Delete the element
>>> s
{2, 3, 4, 5, 'o', 'e', 'l'}
>>> s.remove('www') # If you delete a non-existent element, an error will be reported
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'www'
Copy code
set.pop()
>>> s1 = set("hello world")
>>> s1.pop()
'h'
>>> s1.pop()
'd'
>>> s1.pop() # Note that random deletion
'o'
>>> s1.pop(1) # Cannot delete by index , Because it is disorderly
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop() takes no arguments (1 given)
Copy code
️ Be careful : A collection cannot take out an element , Because the collection does not support subscript index or dictionary access through key value pairs :
>>> s1
{' ', 'e', 'l', 'r', 'w'}
>>> s1[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
Copy code
copyright notice
author[Sissy's father],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201311322027568.html
The sidebar is recommended
- [algorithm learning] 1108 IP address invalidation (Java / C / C + + / Python / go / trust)
- Test platform series (71) Python timed task scheme
- Java AES / ECB / pkcs5padding encryption conversion Python 3
- Loguru: the ultimate Python log solution
- Blurring and anonymizing faces using OpenCV and python
- How fast Python sync and async execute
- Python interface automation test framework (basic) -- common data types list & set ()
- Python crawler actual combat, requests module, python realizes capturing video barrage comments of station B
- Python: several implementation methods of multi process
- Sword finger offer II 054 Sum of all values greater than or equal to nodes | 538 | 1038 (Java / C / C + + / Python / go / trust)
guess what you like
-
How IOS developers learn python programming 3-operator 2
-
How IOS developers learn python programming 2-operator 1
-
[Python applet] 8 lines of code to realize file de duplication
-
Python uses the pynvml tool to obtain the working status of GPU
-
Data mining: Python actual combat multi factor analysis
-
Manually compile opencv on MacOS and Linux and add it to Python / C + + / Java as a dependency
-
Use Python VTK to batch read 2D slices and display 3D models
-
Complete image cutting using Python version VTK
-
Python interface automation test framework (basic) -- common data types Dict
-
Django (make an epidemic data report)
Random recommended
- Python specific text extraction in actual combat challenges the first step of efficient office
- Daily python, Part 8 - if statement
- Django model class 1
- The same Python code draws many different cherry trees. Which one do you like?
- Python code reading (Chapter 54): Fibonacci sequence
- Django model class 2
- Python crawler Basics
- Mapping 3D model surface distances using Python VTK
- How to implement encrypted message signature and verification in Python -- HMAC
- leetcode 1945. Sum of Digits of String After Convert(python)
- leetcode 2062. Count Vowel Substrings of a String(python)
- Analysis of Matplotlib module of Python visualization
- Django permission management
- Python integrated programming -- visual hot search list and new epidemic situation map
- [Python data collection] scripy realizes picture download
- Python interface automation test framework (basic part) -- loop statement of process control for & while
- Daily python, Chapter 9, while loop
- Van * Python | save the crawled data with docx and PDF
- Five life saving Python tips
- Django frequency control
- Python - convert Matplotlib image to numpy Array or PIL Image
- Python and Java crawl personal blog information and export it to excel
- Using class decorators in Python
- Untested Python code is not far from crashing
- Python efficient derivation (8)
- Python requests Library
- leetcode 2047. Number of Valid Words in a Sentence(python)
- leetcode 2027. Minimum Moves to Convert String(python)
- How IOS developers learn Python Programming 5 - data types 2
- leetcode 1971. Find if Path Exists in Graph(python)
- leetcode 1984. Minimum Difference Between Highest and Lowest of K Scores(python)
- Python interface automation test framework (basic) -- basic syntax
- Detailed explanation of Python derivation
- Python reptile lesson 2-9 Chinese monster database. It is found that there is a classification of color (he) desire (Xie) monsters during operation
- A brief note on the method of creating Python virtual environment in Intranet Environment
- [worth collecting] for Python beginners, sort out the common errors of beginners + Python Mini applet! (code attached)
- [Python souvenir book] two people in one room have three meals and four seasons: 'how many years is it only XX years away from a hundred years of good marriage' ~?? Just come in and have a look.
- The unknown side of Python functions
- Python based interface automation test project, complete actual project, with source code sharing
- A python artifact handles automatic chart color matching