Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Python collection set () method

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "Python collection set () method how to use", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Python collection set () method how to use" it!

In python3, data types are roughly divided into the following types according to their mutability and immutability:

Immutable data (3): Number (number), String (string), Tuple (tuple)

Variable data (3): List (list), Dictionary (dictionary), Set (collection).

1. The characteristics of sets

1. Disorder does not repeat no duplicate elements, and the elements are stored out of order (so the collection does not have subscripts and slices), the only function of set is to deduplicate the data.

two。 {} when used, distinguished from the dictionary: a collection when the element in the curly braces is not a key-value pair.

3. The bottom layer of the collection is actually encapsulated by a dictionary.

Establishment of 2.set

You can use curly braces {} or the set () function to create a collection, but note that if you create an empty collection, you must use set () instead of {}, because {} is used to represent empty dictionary types.

1. Use the set () function to create a set set person2 = set (("hello", "jerry", 133 11) ("jerru")) # can pass only one parameter, which can be print (len (person2)) print (person2)'5 {133, 'jerry', 11,' jerru', 'hello'}' 2.add () a=set () a.add ("a") a.add ("b") print (a) 3. Create a set collection with {}. The empty set collection is represented by the set () function and cannot be a = {}. Person = {"student", "teacher", "babe", 123321123} # also various types of nesting, can assign duplicate data, but the storage will deduplicate print (len (person)) # stores 6 pieces of data, the length is 5 Storage is automatically deduplicated print (person) # but displayed is deduplicated 5 {321, 'teacher',' student', 'babe', 123}' # empty set collection is represented by the set () function person1 = set () # indicates empty set The transformation of person1= {} print (len (person1)) print (person1)''0set ()' '4.set collection a = ["awe", "weg", "dawqgg"] c=set (a) print (c) b = "chenshuagege" d=set (b) print (d) al= ("233"," 34455 ") aw=set (al) print (al) 3. Common usage Note # set will also de-duplicate the string because the string belongs to a sequence. Str1 = set ("abcdefgabcdefghi") str2 = set ("abcdefgabcdefgh") print (str1,str2) print (str1-str2) #-you can find the difference set print (str2-str1) # null # print (str1 + str2) # set can't use the + sign = {'dashed,' ified, 'eBay,' faded, 'axed,' baked, 'hacked,' c'} {'dashed,' eBay, 'faded,' a' The common methods of 'gathers,' breads, 'hacks,' c'} {'i'} set () 4.set 4.1 addition, deletion, modification and search operation of the set collection

Add is used to add elements

Update is used for merging collections

Remove reports an error when removing elements that are not in a collection

Discard does not report an error when removing elements that are not in a collection

Del can only be used for the collection itself, not for elements, because elements are cluttered in the collection and have no subscript

Clear empties the collection, leaving the empty collection

Pop randomly deletes an element from the collection

# 1. Add data to the set collection person = {"student", "teacher", "babe", 123321123} person.add ("student") # if the element already exists, it will not report an error, it will not be added, and the string will not be split into multiple elements. Distinguish updateprint (person) person.add ((1Jing 23, "hello")) # can add tuples But it cannot be listprint (person)'{321, 'babe',' teacher', 'student', 123} {(1,23,' hello'), 321, 'babe',' teacher', 'student', 123}' # update for merging collections. Multiple collections can be added to a collection. Data that can be iterar can be added as set collection person.update ("abc") # No string can be added using update, print (person) # will split the string into aline b C three elements'{321,1,3, 'baked,' caged, 'teacher', (1,23,' hello'), 'averse,' babe', 'student', 123}' set1 = set () set1.add ('Wu Zhi Qiankun') set2 = {'jsy',' Daoxiang', 'the price of love', 'big bowl of lasagna'} set2.update (set1) print (set2)''{'big bowl of lasagna' Jsy', 'the price of love', 'Daoxiang','Wu Zhi Qiankun'. Delete data from set person.remove ("student") # Delete print (person) # print ("student") by element if it does not exist, an error will be reported. {321,1,3, 'cased,' baked, (1,23, 'hello'),' teacher', 'babe',' axioms, 123} 'person.discard ("student") # function is the same as remove, the advantage is that if there is no error, ret = person.pop () # delete the last one by default in list and delete one randomly in set. Print (person) print (ret) # pop () returns the deleted item''{1,3, (1,23, 'hello'),' teacher', 'bounded,' averse, 'babe', 123,' c'}''# 3. Update an element in set, because it is unordered, so you can't use the corner sign #, so the general update is to use remove, and then in add#4. If "teacher" in person: print ("true") else: print ("not exist")''true'''#5. The ultimate trick: directly empty setprint (person) person.clear () print (person)''set ()' '4.2 other uses

Intersection union difference operation intersection intersection; union union; difference difference

Operators can be used to represent intersection, union, subtraction intersection-union | subtraction-

# take the intersection of the two b = {1ret=b.intersection 23} a = {23 wa 5} ret=b.intersection (a) print (ret) # take the intersection of the two, and intersection_update will change the content of b. B = {1J 23} a = {23difference 5} b.intersection_update (a) print (b) # union is the combination of two set sets a = {"a", "b", "c"} b = {"a", "wa"} wt=a.union (b) print (wt) # difference means that there is no content b in a. But this does not change the value of an itself, but instead pays ret a = {"12", "14", "234"} b = {"12", "23"} ret=a.difference (b) print (ret) # difference_update means that the content b in an is not available. The content of a will be modified a = {"12", "14", "234"} b = {"12", "23"} a.difference_update (b) print (a) # symmetric_difference to take the same content in two set collections as an edge and then take the contents on both sides a = {"a", "b", "c"} b = {"a", "wa"} ret=a.symmetric_difference (b) print (ret) a.symmetric_difference (b) print (a) # can be expressed as an intersection operator Union, subtraction set2 = {1Power2, 3, 4, 5} set3 = {3, 4, 5, 6, 7, 8, 9} print (set2 & set3) # intersection symbol & print (set2 | set3) # Union symbol | print (set2-set3) # subtraction symbol-b = {1lce23} a = {235.If an and b have a set, return false If there is no collection, return trueret=b.isdisjoint (a) print (ret) b = {1je 23je 5} a = {23je 5} a = {23je 5} # issuperset to indicate whether b is the father of a, if so, output true, if not falseret=b.issuperset (a) print (ret) b = {1M 235e 5} a = {235e 5} b is a child of a, if it is, output true, if not falseret=b.issubset (a) print (ret) 5. List, tuple, dictionary, collection

List: allows repetition, ordering, subscript, slicing

Tuple: repetition is allowed. The elements cannot be added, deleted or modified, but can only be viewed.

Dict: elements in the dictionary exist in the form of key-value pairs. Key: unique value: repeatable

Set: elements are not allowed to repeat and are disordered

5.1 Type conversion between them

1. Lists, tuples, collections, all of which can be transferred to each other

When transferring the list- > tuple,set list to the collection, be careful that there must be no duplicate elements, otherwise the length will change.

Tuple- > list,set

Set- > list,tuple

two。 When the dictionary participates in the transformation, it needs special treatment.

Dict- > list,tuple can only convert the keys of the dictionary, not the value

List- > dict list must be a list or tuple, and there are only two elements in it.

List = [['asides, {1}], (', 2), ('centering, 3)] print (dict (list))

Output:

{'asides: {1},'': 2, 'cations: 3}

5.2 differences between collection and list methods

It is precisely because of the disorder of the set, there is no subscript, so there is some difference between the method and the list.

Append (add elements) extend (to achieve the stitching of lists)

Insert (insert element in a subscript)-> listadd (add element) update (merge of two collections)-> set

Thank you for your reading, the above is the content of "how to use the Python collection set () method". After the study of this article, I believe you have a deeper understanding of how to use the Python collection set () method, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report