In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What is the operation knowledge of list in the Python list? many novices are not very clear about it. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.
What is the list of Python?
A list is an ordered collection of elements that can be added, found, and deleted at any time.
Lists support adding elements of different data types: numbers, strings, lists, tuples, and so on.
The list traverses all the elements through an ordered index, from last to last, and from back to front, the index is [- 1,-n], where n is the length of the list.
The list can be an empty list with no elements, or it can contain a super large number of elements (if memory size is supported).
List_a = [] # empty list, that is, len (list_a) = = 0list_b = [2018, 10, '2018-10-1', ['hi', 1, 2], (33, 44)] # list_b is 5 Contains 2 numeric elements, 1 string element, 1 list element and 1 tuple element len (list_b) = = 5list_b [0] = = list_b [- 5] = = 2018lits_b [3] = = list_b [- 2] = = ['hi', 1,2] lits_b [4] = list_b [- 1] = = (33,44)
How to manipulate the list in Python?
1) create a list:
Wrap elements in parentheses [], separated by commas.
Using the list () method, convert to generate a list.
List generation / list analysis / list derivation to generate a list.
List_a = [1, 2, 3] list_b = list ("abc") # list_b = = ['aura,' baked,'c'] list_c = list ((4, 5, 6)) # list_c = = [4 i for i in list_a 5, 6] list_d = [i for i in list_a] # list_d = = [1, 2, 3] list_e = [iMagj for i in list_a for j in list_c] # list_e = = [4P5 List_f = [ionomj for iCommand j in zip (list_a,list_c)] # list_f = = [4,10,18] list_g = [i for i in list_a if I% 2 = = 0] # list_g = = [2] # combined with range () function Range (start, stop [, step]) list_h = list (range (3)) # list_h = = [0,1,2] list_i = list (range (3jue 7)) # list_i = = [3,4,5,6] list_j = list (range) # list_j = = [3,5,7] # find out the positive integers list_k = list (range (3meme 100meme 3)) # list_k = [3,6,9) divisible by 3 ..., 96, 99]
2) expand the list:
Using the append () method, add a single new element to the end of the list.
Using the insert () method, add the element at the specified location in the list.
Use the + operator to concatenate the two lists into a new list.
Use the extend () method to concatenate one list after another.
# add two elements list_a = [] list_a.append ('happy') # list_a = = [' happy'] list_a.insert (0, 'very') # list_a = = [' very', 'happy'] # the following two expanded list modes: list_1 = [' Illustrated, 'am'] list_2 = [' very' 'happy'] list_3 = list_1 + list_2 # New list list_3 = = [' Illustrated, 'am',' very', 'happy'] list_1.extend (list_2) # original list 1 expansion List_1 = = ['am',' very', 'happy']
3) deletion list and termination list:
Use the del list [m] statement to delete the element at the specified index m.
Use the remove () method to delete the element of the specified value (the first match).
Using the pop () method, take out and delete a single element at the end of the list.
Using the pop (m) method, take out and delete the element whose index value is m.
Use the clear () method to clear the elements of the list. The cup is still there and the water is empty.
Use the del list statement to destroy the entire list. (the cup and water are gone.)
# the following four ways to delete list elements: list_1 = list_2 = list_3 = list_4 = ['am',' am', 'very',' happy'] del list_1 [0] # list_1 = = ['am',' very', 'happy'] list_2.remove (' I') # list_2 = = ['am',' very', 'happy'] list_3.pop () # list_3 = [' ifold, 'am' 'very'] list_4.pop (0) # list_4 = = [' am', 'very',' happy'] # clear and destroy list_a = [1,2,3] list_b = [1,2,3] list_b.clear () # list_b = = [] del list_a # there is no more list_a If you use it again, you will report an error.
4) list slice:
Basic meaning: caused by the I-bit index, take the last n-bit element to the right, and filter by m interval
Basic format: [I: iTunn: M]; I is the starting index value of the slice, which can be omitted when it is the first place in the list; iRecn is the end position of the slice, which can be omitted when it is the last position of the list; m may not be provided, the default value is 1, and 0 is not allowed. When m is negative, the list is flipped. Note: these values can be larger than the length of the list and will not be reported out of bounds.
Li = [1, 4 li 5, 14, 16] # the following words can represent the whole list, where X > = len (li) li [0:] = li [0:] = li [: X] = = li [:] = li [:] = li [- X:] = li [- X:] li [1:5] Take 5-1 bit element li [- 1: 5:2] = = [4jue 6] # from 1, take 5-1 bit element, filter Li [- 1:] = = [16] # take the penultimate element li [- 4 2] = = [9,11] # from the penultimate fourth Take-2-(- 4) = 2-bit element li [:-2] = = li [- len (li):-2] = = [1-len (li):-2] = # start from scratch, take-2-(- len (li)) = 7-bit elements # notice that the list is flipped first, and then intercept li [::-1] = [16pr 14pr. Then filter li [:-5 len (li)) = 4 bits by 2 intervals, and filter li [:: 0] # error report (ValueError: slice step cannot be zero) by 3 intervals by filtering li [:-5 len 1] = = [16 len 14 li 9] # flip the entire list, take-5-(- li (li)) = 4-bit elements, take-5-(- li (li)) = 4-bit elements
5) other operations:
Use the len () method to count the number of all elements. Use the count () method to count the number of elements with a specified value. With the max () method, the maximum value in the statistical element (requires the same element type; numerical type direct comparison, other type comparison id) uses the min () method, and the minimum value in the statistical element (requires the same element type; numerical type direct comparison, other type comparison id) uses the index () method to find the index position (the first match) of the element with the specified value. Using the reverse () method, flip the elements in the list. Using the copy () method, make a shallow copy and generate a new list. Using the deepcopy () method, copy deeply and generate a new list. Sort based on the original list using the sort () method. Use the sorted () method to sort the elements of the original list based on the new list.
List_1 = [2018, 10, '2018-10-1, [' hi', 1, 2], (33, 44)] len (list_1) = = 5list_1.count (10) = = 1 # the number of elements 10 is 1list_1.index (10) = = 1 # the index of element 10 is 1list_1.reverse () # list_1 = = [(33, 44), ['hi', 1,2],' 2018-10-1, 10 2018] # compare shallow copy with deep copy import copylist_a = [2018, 10, '2018-10-1, [' hi', 1,2], (33,44)] list_b = ['hi', 1,2] list_c = list_a.copy () # list_c = = [2018, 10,' 2018-10-1, ['hi', 1,2], (33) ] list_d = copy.deepcopy (list_a) # list_d = = [2018, 10, '2018-10-1, [' hi', 1, 2], (33, 44)] # change the variable object elements list_a [3] .append ('new') # list_a = = [2018, 10,' 2018-10-1, ['hi', 1, 2,' new'], (33) 44)] # variable objects in a shallow copy will change with the original list list_c = = [2018, 10, '2018-10-1', ['hi', 1, 2,' new'], (33, 44)] # variable objects in a deep copy will not change with the original list list_d = = [2018, 10, '2018-10-1, [' hi', 1, 2], (33) 44)] # compare sort () with sorted () list_1 = list_2 = [2 list_1.sort () # the original list changes: list_1 = = [1, 2, 3, 4, 5, 6] list_3 = sorted (list_2) # the original list remains unchanged: list_2 = = [2, 1, 4, 4, 6, 5, 3] List_3 = [1, 2, 3, 4, 5, 6]
Why does the Python list index start at 0?
Authoritative interpretation of the blog post from Guido van Rossum (the father of Python): "Why Python uses 0-based indexing"
To sum up: the index starts at 0, and slicing is elegant.
The essence of the translation is as follows:
One of the reasons I decided to use 0-based indexing in Python is the slice notation.
Let's first look at the use of slices. Perhaps the most common usage is "take the first n-bit element" or "take the last n-bit element from the I-bit index" (the former usage is actually a special use of the starting bit). If these two uses can be implemented without the ugly + 1 or-1 in the expression, it will be very elegant.
Using 0-based indexing, half-open interval slicing, and the default matching interval (which Python eventually did), the slicing syntax for the above two cases becomes very beautiful: a [: n] and a [I: iPren], which is an acronym for a [0: n].
If you use 1-based indexing, then if you want a [: n] to express the meaning of "take the first n elements", you can either use the closed interval slicing syntax or use the slice start bit and slice length as slice parameters in the slice syntax. Half-open interval slicing syntax becomes inelegant when combined with the indexing method of 1-based. Using the closed interval slicing syntax, you have to write the expression a [I: i+n-1] in order to take the last n elements from the I-bit index.
……
Especially when the two slice operation positions are adjacent, and the end index value of the first slice operation is the start index value of the second slice, it is too beautiful to discard. For example, if you want to cut a string into three parts with two positions of iMagnej, the expressions for these three parts will be a [: I], a [I: J] and a [j:].
Indexes for other programming languages?
Programming languages with index from 0: C, C++, Python, Java, PHP, Ruby, Javascript...
Programming languages whose index starts from 1: ABC, Matlab, VB, easy language, most Shell languages.
Programming languages that index from other values: Pascal, Lua...
There are also data that represent sequence structures such as days and months, and various programming languages are divided into different camps.
What are their considerations?
C language: index from 0, can greatly improve the efficiency of memory addressing calculation, a detailed analysis of the reference "[why the subscript of C language array elements starts from 0] (https://blog.csdn.net/bufanq/article/details/51330197)"
Most shell languages: most start with 1. Refer to [stackexchange Q & A] (https://unix.stackexchange.com/questions/252368/is-there-a-reason-why-the-first-element-of-a-zsh-array-is-indexed-by-1-instead-o))
Pascal and Lua: start from 1 by default, but you can change the starting index value because it is said to be more friendly to non-professional developers. Refer to [this Zhihu Q & A] (https://www.zhihu.com/question/19675689/answer/19174752))
The reasons listed above are the most prudent and decent explanations, and the topic should come to an end, because the question of "where should the index start best" is as damaging as "which programming language is the best".
Elegant and beautiful ending: generator expression
List generation is a beautiful and elegant thing, but it has a fatal disadvantage: it loads all elements into memory at once, and when the list is too long, it takes up too much memory resources, and, we usually only need to use a small number of elements, so that most of the memory occupied by unused elements becomes an unnecessary expense.
The generator is a more advanced and elegant thing that uses the principle of "lazy loading" and does not generate a complete list, but iteratively, instantly, and on demand, which not only greatly saves memory space, but also, in theory, it can generate an infinite list!
Most generators are implemented as functions, however, instead of return a value, it generates (yield) a value and suspends the program. Then an element is generated and returned immediately through the next () method, or all elements are generated and returned one by one through the for loop.
Next () is too inefficient and throws a StopIteration exception when the number of calls crosses the limit, and the for loop automatically catches this exception and stops the call, so it is better to use it.
# the generator for calculating the Fibonacci series def fibon (n): a = b = 1for i in range (n): yielda # calculates the first 1000000 numbers using yielda, b = b, a + b #, and generates one number g = fibon (1000000) next (g) # 1next (g) # 1next (g) # 2next (g) # 3next (g) # in sequence through the next () function, and so on, but if you call it more than 1000000 times The first 1000000 numbers of the exception StopIteration# calculation will be reported, and the generated number for x in fibon (1000000): print (x) will be printed one by one through the for loop.
The generator expression is very similar to list generation, except that it changes [] to (), but the principle behind it is very different.
L = [xylene 2 for x in range (5)] # list generation 2 multiples of integers up to 4 g = (xan2 for x in range (5)) # Generator expression type (l) # result: type (g) # result: print (l) # result: [0mem2meme 4mem6 8] print (g) # result: next (g) # 0next (g) # 2next (g) # 4next (g) # 6next (g) # 8next (g) # Traceback (most recent call last):. StopIterationfor x in g:print (x, end='') # result: 0 24 6 8
The above is a summary of all the knowledge related to Python list list operation, including programming technology, operating system, database, web front-end technology and so on.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.