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 to create and convert Python lists

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "the creation and conversion of Python list". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the creation and conversion of Python list".

In this Python tutorial, we will talk about containers in Python. The Python container includes lists, tuples, collections, and dictionaries. There are many methods involved in these data structures, some of the more commonly used methods are introduced here, you don't have to remember every method, just be familiar with the commonly used ones.

First, let's take a look at the list.

I. how to create a list

#-*-coding: utf-8-*-# _ _ author: Demon# date: 1-16-18 8:19 creation of PM# list empty_list_01 = [] # create an empty list empty_list_02 = list () # create an empty list num_list = [1, 2, 3, 4, 5] # create a number list str_list = ['a list,'b' 'c'] # create a list of strings mix_list = [1, 'averse,' abc'] # A list can contain elements of non-fixed type nest_list = [num_list, str_list, mix_list] # list can nest print (num_list) # [1, 2, 3, 4, 5] print (str_list) # ['averse,' b' 'c'] # from the printing results, we can see that the storage of the list is in order # that is, take print (num_list [0]) as it is saved. # the list is accessed by subscript Similar to array 1print (num_list [1]) # list in JAVA, subscript access to array 2print (num_list [2]) # list in JAVA, subscript access to array 3print (num_list [3]) # list in JAVA, and subscript access to array 4print (num_list [4]) # list in JAVA Similar to the array IndexError in JAVA, once it exceeds its length, it throws an exception # print (num_list [5]) # IndexError: list index out of range

2. Common operations in the list

#-*-coding: utf-8-*-# _ _ author: Demon# date: 8:19 on 1-16-18 PM# 1. Num_list = [1, 2, 3, 4, 5] # create a list of numbers for num in num_list: print (num, end= ") # 123456print () # 2. Find the length num_list = [1, 2, 3, 4, 5] # create a number list print (len (num_list)) # number 3. Determine whether the list is empty [important] empty_list = list () num_list = [1,2,3] # using the principle that True is not 0 [recommended method] if not empty_list: # if the list is empty print ("The list is empty") else: print ("The list is not empty") # use length if not len (num_list): print ("The list is empty") else: print ("The list is not empty") # 4. Determine whether an element exists [important] num_list = [1,2,3] if 2 in num_list: print ("in") else: print ("not in") # 5. Add an element empty_list = [] # at the end of append (ele) to create an empty list for s in "Hello": empty_list.append (s) print (empty_list) # ['blocked,' estranged, 'lumped,' l' The above code is also a way to convert a string into a list It's just that the code is complicated. The use of list slicing, such as string slicing, is similar to [important] # usage list [start:end:step] # start can be omitted, the default value is "end" can be omitted, the default is the maximum length # step can be omitted, and the default range is [start, end) That is, left close and right open str_list = ['axiao,' baked,'c'] # create a string list # get the entire list, ['ajar,' baked,'c'] print (str_list [:]) print (str_ list [0:]) print (str_list [: 3]) print (str_list [: 200]) # when the length exceeds No error # get part of print (str_list [0:2]) # ['await,' b'] print (str_ list [0: 2:2]) # ['a'] # 7.sort sort [important] # Note this method does not return a value Is to modify str_list = ["adfas", "dsdfw", "nklo"] str_list.sort () print (str_list) # ['adfas',' dsdfw', 'nklo'] # 8.insert (pos, ele) to insert the element str_list = [' a', 'baked,' c'] # at the specified location to create a string list str_list.insert (2, "we") # ['a' 'baked, 'we', 'c'] print (str_list) # if the position exceeds the length Will not report an error, will insert str_list.insert (20, "we") # [['await,' baked, 'we',' centering, 'we'] print (str_list) # 9.del (pos) to delete the element at the specified location # note that this method is not through the list. The # of the call can be similar to It is not a method in the list class str_list = ['a list, 'baked,' c'] # create a string list del str_list [0] print (str_list) # ['baked,' c'] # del str_list [20] # IndexError: list assignment index out of range# 10.extend (list) or + = merge num_list = [1,2] str_list = ["a" "b"] print (str_list + num_list) # ['a', 'baked, 1, 2] # 11.remove (ele) Delete the specified value str_list = [' a', 'baked,' c'] # create a list of strings str_list.remove ("a") print (str_list) # ['b' 'c'] # str_list.remove ("d") # ValueError: list.remove (x): x not in list# 12.pop (pos) Delete the element str_list = ['averse,' b' at the specified location 'c'] # create a list of strings # str_val = str_list.pop # IndexError: pop index out of rangestr_val = str_list.pop (0) print (str_val) # aprint (str_list) # ['baked,' c'] # 13.reverse () reverse See exercise # 14.count (ele) method to check the number of occurrences of an element str_list = ['abc',' baked, 'cased, "abc"] print (str_list.count ("abc")) # 2

III. Conversion of lists

Other forms of transfer list, using the method of list (otherType). The types of lists that can be transferred are: strings, tuples, etc., as shown in the following code:

Str_01 = "abc" print (list (str_01)) # ['await,' baked,'c'] tuple_01 = (1,2,3) print (list (tuple_01)) # [1,2,3]

List to other forms, usually depends on how other forms support the transformation. One of the more flexible is the conversion from list to string, using the method of join, as shown in the following code:

Str_list = ["a", "b", "c"] print ("," .join (str_list)) # a dint bmam cprint ("" .join (str_list)) # abc

It should be noted that: first, the join method is not a method included in the list, it is a method in the string from the call point of view; second, the join method will report an error if the element in the list is not a string, as shown in the following code:

Num_list = [1,2,3] # print (".join (num_list)) # TypeError: sequence item 0: expected str instance, int found

Common exercises

1. Reversal of list

# method 1: call the reverse () method of the list num_list = [1, 2, 3] num_list.reverse () print (num_list) # [3, 2, 1] # method 2: use slice num_list = [1, 2, 3] for num in num_list [::-1]: print (num) # if you need the format num_list = [1, 2, 3] print ("[") End= ") for num in num_list [: 0print (num, end=", ") if not num_list: # if the list is empty print ("] ") else: print ("% d] "% num_list [0])

two。 How to copy a list to another list

Nest_list = [1,2,3, ['await,' baked,'c']] new_nest_list = nest_list # Direct assignment copy print (new_nest_list) # [1, 2, 3, ['AFP,' baked,'c']] new_nest_list.append ("4") print (new_nest_list) # [1, 2, 3, ['ABA,' baked,'c'] '4'] print (nest_list) # [1, 2, 3, [' await, 'baked,' c'],'4'] # copies of direct assignments affect the original list Is a shallow copy nest_list = [1, 2, 3, ['await,' baked,'c']] new_nest_list = nest_list [:] # sliced print (new_nest_list) # [1, 2, 3, ['ajar,' baked,'c']] new_nest_list.append ("4") print (new_nest_list) # [1, 2, 3, ['ajar,' b' 'c'],' 4'] print (nest_list) # [1, 2, 3, ['await,' baked,'c']] nest_list [- 1] .append ("d") print (new_nest_list) # [1, 2, 3, ['await,' baked, 'cased,' d'],'4'] print (nest_list) # [1, 2, 3, ['await,' b' 'croup,' d']] # use slicing Changing the outermost layer has no effect on the original list, while the inner layer does. This is also a shallow copy of nest_list = [1, 2, 3, ['asides,' baked,'c']] new_nest_list = nest_list.copy () # using the copy method print (new_nest_list) # [1, 2, 3, ['asides,' baked,'c']] new_nest_list.append ("4") print (new_nest_list) # [1, 2, 3, ['a' 'baked,' c'],'4'] print (nest_list) # [1, 2, 3, ['await,' baked,'c']] nest_list [- 1] .append ("d") print (new_nest_list) # [1, 2, 3, ['ABA,' baked, 'cased,' d'],'4'] print (nest_list) # [1, 2, 3, ['a'' 'baked,' cached,'d']] # using copy Changing the outermost layer has no effect on the original list, while the inner layer does. This is also a shallow copy # if you want to achieve a deep copy, you need to use the deepcopy method in the copy module, as detailed in the article

3. Sort the list

The simple sorting of lists usually uses the list.sort () method. But this sort method is relatively flexible to use. Its full definition is as follows:

Sort (*, key=None, reverse=False)

Key specifies a function name, and this function can only accept one argument.

Reverse specifies how to sort

X = ['bc',' essmm', 'mdsfm',' ss'] x.sort (key=str.lower) print (x) # ['bc',' essmm', 'mdsfm',' ss'] y = [3,2,8,0,1] y.sort (reverse=True) print (y) # [8,3,2,1,0]

As you can see, sorting using the list.sort () method is a method that comes with the called list, and it acts on the original list and does not return a value. If we want to get a new sorted list, we need to use the sorted () method.

Thank you for your reading, the above is the content of "the creation and conversion of Python list". After the study of this article, I believe you have a deeper understanding of the creation and conversion of Python list, 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