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 is the most common problem with the Python list

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

Share

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

Python list what is the most common problem, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

List is one of the most widely used data results in Python. How to operate the list efficiently is the key to improve the efficiency of the code. This paper summarizes some of the most common problems in python lists, hoping to be helpful.

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--> 45

2. What's 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] # 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 copy is a 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] 10

7. 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, when the following table index of the list is exceeded, the exception of IndexError is thrown > a.pop (7) Traceback (most recent call last): File ", line 1, in IndexError: pop index out of range

9. How to connect two lists

Listone = [1,2,3] listtwo = [4,5,6] mergedlist = listone + listtwoprint (mergelist) > [1,2,3,4,5,6]

The list implements operator overloading of +, so that + not only supports the addition of values, but also supports 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 get an element in the list randomly

Import randomitems = [8,23,45,12,78] > > random.choice (items) 78 > random.choice (items) 45 > random.choice (items) 12 after reading the above, have you mastered what are the most common problems in the Python list? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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