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

What are the most common problems in the Python list

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "what are the most common problems in the Python list". In the daily operation, I believe many people have doubts about the most common problems in the Python list. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts of "what are the most common questions in the Python list?" Next, please follow the editor to study!

1. How to access the list subscript index when iterating over the list

Regular version:

Items = [8,23,45] for index in range (len (items)): print (index, "-->", items [index]) > > 0-- > 81-- > 232-- > 45

Elegant version:

For index, item in enumerate (items): print (index, "-->", item) > > 0-- > 81-- > 232-- > 45

Enumerate can also specify when to start the first element of an element, the default is 0, or you can specify to start with 1:

For index, item in enumerate (items, start=1): print (index, "-->", item) > > 1-- > 82-- > 233--> 452.What is the difference between append and extend

Append means to append some data to the end of the list as a new element, and its parameters can be any object.

X = [1,2,3] y = [4,5] x.append (y) print (x) > [1,2,3, [4,5]]

The parameter of extend must be an iterable object, which means that all elements in the object are appended to the end of the list one by one.

X = [1,2,3] y = [4,5] x.extend (y) print (x) > > [1,2,3,4,5] # is equivalent to: for i in y: x.append (I) 3, check whether the list is empty

Regular version:

If len (items) = 0: print ("empty list") or if items = = []: print ("empty list")

Elegant version:

If not items: print (empty list) 4. How to understand slicing

Slicing is used to get a subset of the specified norms in the list, and the syntax is very simple.

Items [start:end:step]

The element from start to end-1 location. Step represents the step size. The default is 1, which means continuous fetching. If step is 2, it means fetching every other element.

A = [1,2,3,4,5,6,7,8,9,10] > > a [3:8] # elements between positions 3 and 8 [4, 5, 6, 7, 8] > > a [3:8:2] # elements between positions 3 and 8 Get every other element [4,6,8] > a [: 5] # omitting start means starting from the 0th element [1,2,3,4,5] > a [3:] # omitting end to the last element [4,5,6,7,8,9,10] > > a [:] # is equivalent to copying a list This kind of copy belongs to shallow copy [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 5, how to copy a list object

The first method:

New_list = old_list [:]

The second method:

New_list = list (old_list)

The third method:

Import copy# shallow copy new_list = copy.copy (old_list) # Deep copy new_list = copy.deepcopy (old_list) 6, how to get the last element in the list

The elements in the indexed list support not only positive numbers but also negative numbers. A positive number indicates that the index starts on the left side of the list, and a negative number indicates that the index starts on the right side of the list. There are two ways to get the last element.

> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > a [len (a)-1] 10 > > a [- 1] 107, how to sort the list

There are two ways to sort a list, one is the sort that comes with the list, and the other is the built-in function sorted. Complex data types can be sorted by specifying the key parameter. A list of dictionaries sorted by the age field in the dictionary element:

Items = [{'name':' Homer', 'age': 39}, {' name': 'Bart',' age': 10}, {"name": 'cater',' age': 20}] items.sort (key=lambda item: item.get ("age") print (items) > [{'age': 10,' name': 'Bart'}, {' age': 20, 'name':' cater'} {'age': 39,' name': 'Homer'}]

The list has a sort method, which is used to reorder the original list, specifying the key parameter, key is an anonymous function, and item is a dictionary element in the list. We sort according to the age in the dictionary. The default is to sort in ascending order, and specify reverse=True to sort in descending order.

Items.sort (key=lambda item: item.get ("age"), reverse=True) > [{'name':' Homer', 'age': 39}, {' name': 'cater',' age': 20}, {'name':' Bart', 'age': 10}]

If you do not want to change the original list, but generate a new ordered list object, you can have a built-in function sorted, which returns the new list

Items = [{'name':' Homer', 'age': 39}, {' name': 'Bart',' age': 10}, {"name": 'cater',' age': 20}] new_items = sorted (items, key=lambda item: item.get ("age") print (items) > [{'name':' Homer', 'age': 39}, {' name': 'Bart',' age': 10} {'name':' cater', 'age': 20}] print (new_items) > [{' name': 'Bart',' age': 10}, {'name':' cater', 'age': 20}, {' name': 'Homer',' age': 39}] 8, how to remove elements from a list

There are three ways to delete elements from a list

Remove removes an element and can only remove elements that appear for the first time

> a = [0,2,2,3] > > a.remove (2) > > a [0,2,3] # if the element to be removed is not in the list, throw a ValueError exception > a.remove (7) Traceback (most recent call last): File ", line 1, in ValueError: list.remove (x): x not in list

Del removes an element based on the specified location

> a = [3, 2, 2, 1] # remove the first element > del a [1] [3, 2, 1] # when the IndexError exception is exceeded in the following table index of the list > del a [7] Traceback (most recent call last): File ", line 1, in IndexError: list assignment index out of range

Pop is similar to del, but the pop method can return removed elements

> a = [4,3,5] > > a.pop (1) 3 > > a [4,5] # similarly, throw IndexError exception > a.pop (7) Traceback (most recent call last): File ", line 1, in IndexError: pop index out of range9, how to join two lists listone = [1,2,3] listtwo = [4,5,6] mergedlist = listone + listtwoprint (mergelist) > [1,2,3,4,5,6]

The list implements the operator overloading of +, so that + supports not only the addition of values, but also the addition of two lists. As long as you implement the _ _ add__ operation of an object, any object can implement the + operation, for example:

Class User (object): def _ init__ (self, age): self.age = age def _ repr__ (self): return 'User (% d)'% self.age def _ add__ (self) Other): age = self.age + other.age return User (age) user_a = User (10) user_b = User (20) c = user_a + user_bprint (c) > > User (30) 10, how to randomly get an element in the list import randomitems = [8, 23, 45, 12, 78] > random.choice (items) 78 > > random.choice (items) 45 > > random.choice (items) 12 so far The study on "what are the most common problems in the Python list" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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