程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python notes 04

編輯:Python

Python04

Python04 Create list of list characteristics of list get the index of the specified element get a single element in the list get multiple elements in the list -- Slicing operation list element querying operation list element adding operation list element deleting operation list element modifying operation list element sorting operation list generating formula

list

Why do I need a list

  • A variable can store an element , And the list is a “ Big container ” Can be stored n Multiple elements , The program can easily operate the data as a whole

  • Lists are equivalent to arrays in other languages

# Flow control statement :break And continue Use in double cycle
for i in range(5):  # Represents the outer loop execution 5 Time
   for j in range(1,11):
       if j % 2 == 0:
           continue
       print(j, end='\t')
   print()

List creation

  • Use brackets

  • Call built-in functions list()

''' The first way to create a list , Use brackets '''
lst = ['hello', 'world', 98]
''' The second way to create a list , Use built-in functions list()'''
lst2 = list(['hello', 'world', 98])

Features of lists

  • The list elements are sorted in order

  • Index maps the only data

  • Lists can store duplicate data

  • Mixed storage of any data type

  • Dynamically allocate and reclaim memory as needed

''' The first way to create a list , Use brackets '''
lst = ['hello', 'world', 98, 'hello']
print(lst)
print(lst[0], lst[-4])
''' The second way to create a list , Use built-in functions list()'''
lst2 = list(['hello', 'world', 98])

Gets the index of the specified element

  • If there are multiple identical elements in the list , Only the index of the first element of the same element in the list is returned

  • If the element of the query does not exist in the list , It will appear ValueError

  • It can also be in the specified start and stop Search between

lst = ['hello', 'world', 98, 'hello']
print(lst.index('hello'))
# print(lst.index('Python'))   # ValueError: 'Python' is not in list
# print(lst.index('hello', 1, 3)) # ValueError: 'hello' is not in list
print(lst.index('hello', 1, 4))  # 3

Get a single element in the list

  • Forward index from 0 ~ n-1

  • Reverse index from -n ~ -1

  • The specified index does not exist , when indexError

lst = ['hello', 'world', 98, 'hello', 'world', 234]
# Get the index as 2 The elements of
print(lst[2])
# Get the index as -3 The elements of
print(lst[-3])
# Get the index as 10 The elements of
# print(lst[10]) # IndexError: list index out of range

Get multiple elements in the list -- Slicing operation

  • Grammar format : List name 【start:stop:step】

  • step When it's negative : The first element of the slice defaults to the last element of the list ; The last element of the slice defaults to the first element of the list

lst = [10, 20, 30, 40, 50, 60, 70, 80]
# start = 1, stop = 6, step = 1
# print(lst[1:6:1]) # [20, 30, 40, 50, 60]
print(" Original list :", id(lst))
lst2 = lst[1:6:1]
print(" Cut segment :", id(lst2))
print(lst[1:6])   # [20, 30, 40, 50, 60] # The default step size is 1
print('------------step When the step size is positive -----------')
print(lst[1:6:])  # The default step size is 1
# start = 1, stop = 6, step = 2
print(lst[1:6:2])  # [20, 40, 60]
# start By default , stop = 6, step = 2
print(lst[:6:2])  # [10, 30, 50]
# start 1, stop By default , step = 2
print(lst[1::2])  # [20, 40, 60, 80]
print('------------step When the step size is negative -----------')
print(' Original list :', lst)
print(lst[::-1])  # Output the list elements in reverse order [80, 70, 60, 50, 40, 30, 20, 10]
# start 7, stop Omit , step = -1
print(lst[7::-1])  # [80, 70, 60, 50, 40, 30, 20, 10]
# start 6, stop 0, step = -2
print(lst[6:0:-2])  # [70, 50, 30]

Query operation of list elements

  • Determine whether the specified element exists

print('p' in 'python')  # True
print('k' not in 'python')  # True
lst = [10, 20, 'python', 'hello']
print(10 in lst)  # True
print(100 in lst)  # False
print(10 not in lst)  # False
print(100 not in lst)  # True
  • Traversal of list elements

lst = [10, 20, 'python', 'hello']
for item in lst:
   print(item)

Addition of list elements

  • append(): Add an element at the end of the list

  • extend(): Add at least one element at the end of the list

  • insert(): Add an element anywhere in the list

  • section : Add at least one element anywhere in the list

# Add an element to the end of the list
lst = [10, 20, 30]
print(' Before adding :', lst)
print(id(lst))
lst.append(100)
print(' After adding :', lst)
print(id(lst))
lst2 = ['hello', 'world']
# lst.append(lst2) # take lst2 Add to the end of the list as an element
# print(lst) # [10, 20, 30, 100, ['hello', 'world']]
lst.extend(lst2) # Add more than one element at a time to the end of the list
print(lst) # [10, 20, 30, 100, 'hello', 'world']
lst.insert(1, 90) # Add an element anywhere
print(lst) # [10, 90, 20, 30, 100, 'hello', 'world']
lst3 = [True, False, 'hello']
# Add... Anywhere n Multiple elements
lst[1:] = lst3
print(lst) # [10, True, False, 'hello']

Deletion of list elements

  • remove(): Delete one element at a time ; Duplicate elements delete only one , There is no element explosion ValueError

  • pop(): Deletes an element at a specified index position ; If the specified element does not exist, it will be exploded IndexError; Do not specify element bits , Then delete the last element in the list

  • section : Delete at least one element at a time , Slicing produces a new list object

  • clear(): Clear the list

  • del: Delete list

lst = [10, 20, 30, 40, 50, 60, 30]
lst.remove(30) # Remove an element from the list , If there are repeating elements , Remove only the first element
print(lst) # [10, 20, 40, 50, 60, 30]
# lst.remove(100) # ValueError: list.remove(x): x not in list
# pop() Remove elements according to index
lst.pop(1)
print(lst) # [10, 40, 50, 60, 30]
# lst.pop(5) # IndexError: pop index out of range If the specified index location does not exist , Throw an exception
lst.pop() # If no parameters are specified ( Indexes ), The last element of the list will be deleted
print(lst)
print('--------------- Slicing operation - Delete at least one element , A new list object will be generated -----------------')
new_list = lst[1:3]
print(' Original list :',new_list) # Original list : [40, 50]
''' No new list objects are generated , Instead, delete the contents of the original list '''
lst[1:3] =[]
print(lst) # [10, 60]
''' Know all the elements in the list '''
lst.clear()
print(lst) # []
'''del Statement to delete a list object '''
del lst
# print(lst) # NameError: name 'lst' is not defined

Modification of list elements

  • Assign a new value to the element of the specified index

  • Assign a new value to the specified slice

lst = [10, 20, 30, 40]
# Modify one value at a time
lst[2] = 100
print(lst) # [10, 20, 100, 40]
lst[1:3] = [300, 400, 500, 600]
print(lst) # [10, 300, 400, 500, 600, 40]

Sorting of list elements

  • call sort() Method , By default, all elements in the list are sorted from small to large , You can specify reverse = True, Sort in descending order

  • Call built-in functions sorted(). You can specify reverse = True, Sort in descending order , The original list doesn't change

lst = [20, 40, 10, 98, 54]
print(' The list before sorting ', lst, id(lst))
# Start sorting , Call the of the list object sort Method , Default ascending order
lst.sort()
print(' Sorted list ', lst, id(lst)) # [10, 20, 40, 54, 98]
# By specifying keyword parameters , Sort the elements in the list in descending order
lst.sort(reverse=True) # reverse=True Represents a descending sort reverse=False Indicates ascending sort
print(lst) # [98, 54, 40, 20, 10]
lst.sort(reverse=False) # reverse=True Represents a descending sort reverse=False Indicates ascending sort
print(lst) # [10, 20, 40, 54, 98]
print('---------- Use built-in functions sorted() Sort list , A new list object will be generated --')
lst = [20, 40, 10, 98, 54]
print(' The list before sorting ', lst) # The list before sorting [20, 40, 10, 98, 54]
# Start sorting
new_list = sorted(lst)
print(' Sorted list ', new_list) # Sorted list [10, 20, 40, 54, 98]
# Specify keyword parameters , Realize the descending sorting of list elements
desc_list = sorted(lst, reverse=True)
print(desc_list) # [98, 54, 40, 20, 10]

List generator

  • abbreviation : The formula for generating the list

  • Be careful :“ Expressions that represent list elements ” It usually contains custom variables

lst = [i*i for i in range(1,10)]
print(lst) # [1, 4, 9, 16, 25, 36, 49, 64, 81]
''' The elements in the list are 2,4,6,8,10'''
lst2 = [2*i for i in range(1,6)]
print(lst2) # [2, 4, 6, 8, 10]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved