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

Case Analysis of Python Collection and Dictionary data types

2025-01-14 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 and dictionary data type case analysis", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "Python collection and dictionary data type case analysis"!

Preface

The collection data type is an unordered aggregation of simple objects, and the elements in the collection are not duplicated. Collections in Python include mutable collection objects (set) and immutable collection objects (frozenset). A dictionary is a data structure with key-value pairs. Each key cannot be repeated, and its value can be queried according to the key of the dictionary. The appearance of the two brothers is made up of {} for parcels. And the underlying principles have certain commonality. Their underlying implementations generally use hash tables.

First, collection type 1. Define

Set data types are divided into two types: variable set (set) and immutable set (frozenset).

The elements in the collection cannot be repeated and are out of order. (because objects are stored in the collection in the form of hash objects)

Immutable objects should be placed in the collection (numeric data types, string tuples, immutable collections)

The representation of an empty collection is set (). {} is the representation of an empty dictionary.

You can use in / not in to determine whether an element is in the collection.

two。 Collection usage mode

The use of collections is somewhat similar to that learned in high school. In other words, mathematical set intersection, union, complement and difference operations can be applied to Python sets. The representation is as follows

Suppose that the set has four intercourse: a = {1mage2re3}, B = {2rec 3je 4}, C = {3pr 4je 5}, D = {1je 2je 3je 4}:

A | B | C = {3}

And:

Atom B = {1pm 2pm 3pm 4}

Supplement:

A ^ D = {4}

Difference

Amurb = {1}

These methods can be used to judge whether there is the same element and whether it has an inclusion relationship.

3. Set derivation

When talking about lists earlier, we talked about list derivation, which can directly generate your own desired list. Today we're going to talk about the derivation of the set list.

Deductive grammar:

{variable general formula for i in sequence [judgment condition]}

For example, the square of the following formula

Print ({ibidi for i in range (10) if I% 2 percent 0}) 4. Variable set

Mutable sets are created with set (the underlying layer of the mutable set is still a hash table, so only immutable objects can be stored) print (set ([1mem2mem3]))

There are a series of methods for creating objects. The functions add (x), remove (x), discard (x), pop () and clear () correspond to adding elements, removing elements (no throwing exception), removing elements, popping up elements randomly, and emptying the collection.

Actual operation code:

'' collection set, the underlying layer is still a hash table, unordered and non-repeatable (add, delete, create collection) # declaration method S1 = {123 for i in range type (S1) print (S2) print (S2) Type (S2)) print (S3) # determines whether the set is the same (comparing the internal elements) print (s1==s2) print (s1==s3) # add # for one increase s1.add (123123) print (S1) # suitable for adding multiple elements # add the string directly to s1.update (['world','milk']) s1.update ((' world1','milk1')) # add the string to s1.update ('world3') 'milk3') print (S1) # delete # delete elements, if not, throw exception # s1.remove (777) # Delete elements, if not, do not throw exceptions Nones1.discard (888) print (s1.discard (777)) print (S1) # randomly delete an element (cannot pass parameters) s1.pop () # clear all elements s1.clear () # empty sets print (S1)' 'sets, hand in And Difference set, union difference set subset, superset Whether the elements are the same''s4=set (S2) s5=set (S2) s4.add (' joso') s5.add ('pink') # S2 is a subset of S4 print (s2.issubset (S4)) # S2 is a superset of S4 print (s2.issuperset (S4)) # whether the two sets and elements are different print (s5.isdisjoint (S4)) # intersecting print (' -') Print (s4.intersection (S2)) print (S4 & S2) # Union print ('-') print (s4.union (S5)) print (S4 | S5) # difference print (s4.difference (S5)) print (s4-s5) # symmetric difference print (s4.symmetric_difference (S5)) print (S4 ^ S5) II. Dictionary type 1. Define

A dictionary is a mapping relationship between keys and values, so it is sometimes called a mapping data type. The key of the dictionary is a hash data type (immutable), the value is of any type, and there can be only one key in a dictionary, and the value can be repeated and can be taken at will. The corresponding value can be obtained through the key.

The general form of key-value pairs is key: value.

So the general form of the dictionary is {key 1: value, key 2: value, key 3: value. }

To create a dictionary, you can directly use the literal quantity {key 1: value, key 2: value, key 3: value. }, or you can create it using dict.

Dict supports dictionary to dictionary and sequence to dictionary.

two。 The way dictionaries are used

When using the dictionary, you can get the list of keys, values and [keys, values] separately.

The way is:

Dic.keys () # get key list

D.values () # get the list of values

D.items () # gets the list of key values in tuple form

The dictionary can use in / not in to determine whether the dictionary contains a key.

The dictionary object has a series of methods:

Clear () # clear elements

Copy () # copy dictionary

Get (k) # get the value according to the key

Pop (k) # if the key exists, delete and return the value. No exception is thrown.

Pop (k _ camera v) # if the key exists, delete and return the value, no V is returned

Setdefault (KJE v) # returns the value of the k key if it exists, adds the k key and assigns the value None if it does not exist

Update () # pass in dictionary or key-value pair update operation

3. Dictionary derivation

Dictionary derivation is similar to list derivation and set derivation, except that it has two values {KRV for k in. For v in... }

{x:x*x for x in range (10) if x% 2 for y in range 0} {x for x in range (10) for y in range (10m 20)} 4. Code practice what's the difference between dictionaries and lists in contrast learning? The list is that the data in the square bracket list is a single existing order that can be repeated in the dictionary, and the data in the curly braces dictionary is a pair of unordered keys and value pairs that cannot be written indiscriminately, and if the key is repeated, the values will overwrite the data in the dictionary out of order, and the underlying principle is the hash table. Using hash table to realize the creation method of key value corresponding to''# dictionary-when the same key in the # dictionary corresponds to different values, the previous values will be overwritten by s = {'name':' Zhang San', 'paassward':'888888','name':' Makabaka'} # dictionary creation method 2 ss = dict (user='pig',passward='123123') # dictionary creation method 3 (list creation) T1 = ['username'' 'passward'] T2 = [' Tom','1980'] # upper Lower is an all-uppercase, all-lowercase function sss= {t1.upper (): t2.lower () for T1 ss,type T2 in zip (T1 ss,type T2)} # print shows dictionary type print (s) print (ss,type (s)) print (sss,type (s)) # addition / modification of dictionary elements # since there can be only one key in the dictionary, when a key corresponds to a new value Overwrite # that is, modify the value corresponding to the original key s ['name'] =' Li Si 'print (s) # or use a key that didn't exist before to create a new effect s [' age'] = '20'print (s) # get dictionary value # get all keys keyS=s.keys () print (keyS) # get all values valueS=s.values () print (keyS) ValueS) # get all key-value pairs iteM=s.items () print (iteM) # give key get value dictionary name [key]-cannot find an error print (s ['paassward']) # give key get value dictionary name. Get ()-cannot find what print (s.get (' paassward')) print (s.get ('qwe')) can be specified ('not found') # determine whether it is in the dictionary (key values can be judged) print ('paassward' in sdescription 888888 in s) # clear dictionary element del s [' name'] print (s) # clear dictionary s.clear () print (s) # dictionary traversal # temp as the key in the dictionary Then look for the value for temp in ss: print (temp,ss [temp], ss.get (temp)) in the dictionary. Thank you for reading. The above is the content of "instance Analysis of Python Collection and Dictionary data types". After the study of this article, I believe you have a deeper understanding of the problem of instance analysis of Python collection and dictionary data types, 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