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 Python manipulates lists, meta-ancestors, dictionaries, collections

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article will explain in detail how Python operates lists, meta-ancestors, dictionaries and collections. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

1. List list

Is a data structure that deals with an ordered set of items, that is, you can store a sequence of items in a list. Suppose you have a shopping list of what you want to buy, so you can easily understand the list. It's just that on your shopping list, everything may have its own line.

In Python, you separate each item with a comma. The items in the list should be included in square brackets so that Python knows that you are specifying a list.

Once you have created a list, you can add, delete, or search for items in the list. Since you can add or delete items, we say that lists are mutable data types, that is, this type can be changed

# Shopping list shoplist = ['Apple', 'mango', 'carrot', 'banana'] basic operation print ('I have', len (shoplist), 'items on my shopping list.') print ('they are:'), # prompt for item in shoplist: print (item) print ('I also bought rice.') shoplist.append ('rice') print ('now my shopping list is'' Shoplist) # ['apple', 'mango', 'carrot', 'banana', 'rice']

Basic operation-- increase

Append append

Li = ['apple', 'mango', 'carrot', 'banana'] li.append ('rice') print (li) # ['apple', 'mango', 'carrot', 'banana', 'rice'] li.append (1) # ['apple', 'mango', 'carrot', 'banana', 'rice' 1] print (li.append ('hello')) # None: no return value Li.append () is just a method, action print (li) # ['apple', 'mango', 'carrot', 'banana', 'rice', 1, 'hello']

* * insert * * insert

Li = ['Apple', 'Mango', 'carrot', 'Banana'] li.insert (3 'strawberry') print (li) # ['Apple', 'Mango', 'Carrot', 'Strawberry', 'Banana']

* * extend * * append to the end

Li = ['apples', 'mangoes', 'carrots', 'bananas'] li.extend ('cc') print (li) # [' apples', 'mangoes', 'carrots', 'bananas', 'caches,' c'] li.extend ([1d2, 3]) print (li) # ['apples', 'mangoes', 'carrots', 'bananas', 'caches,' c' c' Li.extend (123) # error: numbers cannot be iterated print (li) # TypeError: 'int' object is not iterable

Application example:

Enter the employee's name continuously, enter QCompQ to exit and print the list

Li = [] while True: username = input ("Please enter the name of the employee to be added:") if username.strip () .upper () = 'Qothers: break li.append (username) print (li) print (li)

Running result:

]

List-delete

Remove: delete by element

Li = ['apple', 'mango', 'carrot', 'banana'] li.remove ('mango') print (li) # ['apple', 'carrot', 'banana']

Pop: delete by index-there is a return value

Li = ['apple', 'mango', 'carrot', 'banana'] name = li.pop (1) # return value print (name,li) # mango ['apple', 'carrot', 'banana'] name = li.pop () # if you don't write the index, the last print (name,li) # banana ['apple', 'carrot']

Clear: empty

Li = ['apple', 'mango', 'carrot', 'banana'] li.clear () print (li) # []

Del: deletin

Li = ['apple', 'mango', 'carrot', 'banana'] del li [2:] print (li) # ['apple', 'mango'] del li # after deletion, it no longer exists. Print error print (li) # NameError: name 'li' is not defined

Cyclic deletion

Li = [11, 22, 33, 44, 55] for i in range (len (li)): print (I) del li [0] print (li)

List-change

* * li [index] * * = 'modified content'

Li = ['apple', 'mango', 'carrot', 'banana'] li [0] = 'dragon fruit' # change the position with index 0 to 'dragon fruit' print (li) # ['dragon fruit', 'mango', 'carrot', 'banana']

* * li [slice] * * = 'modified content' (iterative: divided into the smallest elements, added one by one)

Li = ['apple', 'mango', 'carrot', 'banana'] li [0:2] = 'abcd' # replace index 0-2 with abcd, and then slice and iterate print (li) / / [' await, 'baked,' crested, 'dashed,' carrot', 'banana'] li [0:3] = ['I', 'like', 'eat' 'fruit'] print (li) / / [I', 'like', 'eat', 'fruit', 'dice', 'carrots', 'banana' list-check

From beginning to end: for loop

Li = ['apple', 'mango', 'carrot', 'banana'] for i in li: print (I)

One: index

Li = ['apple', 'mango', 'carrot', 'banana'] print (li [1]) # mango

One segment: slicing

Li = ['apples', 'mangoes', 'carrots', 'bananas'] print (li [0:2]) # ['apples', 'mangoes', 'carrots'] list-- nested li = ['apples', 'mangoes', 'carrots', ['aplomaniology'. Banana] print (li [2] [1]) # Loli [3] [0] .upper () # change the first element of the fourth element list in the list to uppercase print (li) # ['apple', 'mango', 'carrot', ['banana,' baked,'c'] list-- print in a loop # index starts from zero by default li = ['alex','taibai','wusir''] list 'egon'] for i in li: print (li.index (I), I) specifies that the index starts running from 1000.Result: other common operations

Convert split**:** string to list str--- > list

S = 'xcsd_cdc_eht_' print (s.split ('_')) / / ['xcsd',' cdc', 'eht',' Mu'] S1 ='xc sdc dc eht Zeng Mu 'print (s1.split ('')) / / ['xc',' sdc', 'dc',' eht','Mu']

* * convert the join:** list to the string list--- > str

Join (iterable object iterable) split

Iterable object iterable:list,str, meta-ancestor

Li = ['xcsd',' cdc', 'eht',' wood'] s = '.join (li) print (s) # xcsdcdceht wood S1 =' _ '.join (li) print (S1) # xcsd_cdc_eht_ wood

Range: regardless of head and tail-equivalent to an ordered list of numbers (can be reversed, plus step size)

For i in range (2jue 6): print (I)

Application example:

Print in a loop. When you encounter a list in a list, you also need to print in a loop.

Li = [1Jing 2 Jing 3 Jing 5 Magistrate], 'afds'] for i in li: if type (I) = = list: for n in i: print (n) else: print (I)

Running result:

Second, Yuanzu

Tuples are very similar to lists, except that tuples are as immutable as strings, that is, you cannot modify tuples. Tuples are defined by items separated by commas in parentheses.

Tuples are usually used to enable statements or user-defined functions to safely adopt a set of values, that is, the values of the tuples used do not change.

Tu1 = (1) tu2 = (1,) print (tu1,type (tu1)) # 1 print (tu2,type (tu2)) # (1,) tu3 = ([1]) tu4 = ([1],) print (tu3,type (tu3)) # [1] print (tu4,type (tu4)) # ([1],) the basic operation of the tuple tu = 'egon') print (tu [2]) # 3print (tu [0:2]) # (1,2) for i in tu: print (I) # circularly print meta-ancestor dictionary

A dictionary is similar to an address book where you look up addresses and contact details through contact names, that is, we associate keys (names) with values (details). Note that the key must be unique, just like if two people happen to have the same name, you can't find the correct information.

Note that you can only use immutable objects (such as strings) as dictionary keys, but you can use immutable or mutable objects as dictionary values.

Basically, you should only use simple objects as keys.

Key-value pairs are marked in the dictionary as follows: d = {key1: value1, key2: value2}.

Note that their key / value pairs are separated by colons, while individual pairs are separated by commas, all of which are included in curly braces

Dict key (key) must be an immutable data type, but hash value (value) any data type

Dict advantages: binary search to query and store a large amount of relational data features: set3) # Trueprint (set4.issuperset (set3)) # truth 5, public method sorting

Forward sort: sort ()

Li = [1, 5, 4, 2, 6, 7, 3] li.sort () print (li) # [1, 2, 3, 4, 5, 6, 7]

Sort in reverse order: li.sort (reverse = True)

Li = [1, reverse 5, 4, 2, 6, 7, 3] li.sort (reverse = True) print (li) # [7, 6, 5, 4, 3, 2, 1]

Reverse: li.reverse ()

Li = [1, print 5, 4, 2, 6, 7, 3] li.reverse () print (li) # [3, 7, 6, 2, 4, 5, 1] add:

Sort the list of strings-sort by the ASCII code corresponding to the first character of the string

Li = ['ojhy','asa','cvd','hdk'] li.sort () print (li) # [' asa','cvd','hdk', 'ojhy'] the number of occurrences of count () elements li = [' xcsd', 'cdc',' wood', [1,5,2], 'eht' Num = li.count ('Mu') print (num) # 2 the length of the len () calculation list li = ['xcsd',' cdc','Mu', [1,5,2], 'eht',' Mu'] l = len (li) print (l) # 6: the list length is 6li.index ('element') View Index li = ['xcsd',' cdc'' The index of 'Xinchen', [1,5,2], 'eht',' Xinchen] print (li.index ('eht')) # 4 li.index (' eht')'is 4 yuan six. Differences and similarities and differences

List list tuple tuple collection set dictionary dict can read-write repeat whether it is a storage mode value key (cannot be repeated) key-value pair (key cannot be repeated) whether the key-value pair (key cannot be repeated) is ordered and unordered automatic initialization [1prima] (1) set ([1jue 2]) or {1prit 2} {'afiuza 1 Add append read-only addd ['key'] =' value' read element 1 [2:] t [0] No d ['a'] about how Python manipulates lists, meta-ancestors, dictionaries, collections Hope that the above content can be helpful to you, so that you can learn more knowledge, if you think the article is good, please share it for more people to see.

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

Internet Technology

Wechat

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

12
Report