当前位置:网站首页>Use list
Use list
2022-06-24 15:16:00 【User 8442333】
The following code demonstrates how to define a list 、 Use subscripts to access list elements and add and delete elements .
def main():
list1 = [1, 3, 5, 7, 100]
print(list1)
list2 = ['hello'] * 5
print(list2)
# Calculate the length of the list ( Element number )
print(len(list1))
# Subscript ( Indexes ) operation
print(list1[0])
print(list1[4])
# print(list1[5]) # IndexError: list index out of range
print(list1[-1])
print(list1[-3])
list1[2] = 300
print(list1)
# Additive elements
list1.append(200)
list1.insert(1, 400)
list1 += [1000, 2000]
print(list1)
print(len(list1))
# Remove elements
list1.remove(3)
if 1234 in list1:
list1.remove(1234)
del list1[0]
print(list1)
# Empty list elements
list1.clear()
print(list1)
if __name__ == '__main__':
main()Just like a string , The list can also be sliced , Through slicing, we can copy the list or take out part of the list to create a new list , The code is as follows .
def main():
fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pitaya', 'pear', 'mango']
# Loop through list elements
for fruit in fruits:
print(fruit.title(), end=' ')
print()
# List slice
fruits2 = fruits[1:4]
print(fruits2)
# fruit3 = fruits # There is no copy list, only new references are created
# You can copy the list through the full slice operation
fruits3 = fruits[:]
print(fruits3)
fruits4 = fruits[-3:-1]
print(fruits4)
# You can get a copy of the inverted list by reverse slicing
fruits5 = fruits[::-1]
print(fruits5)
if __name__ == '__main__':
main()The following code implements the sorting operation of the list .
def main():
list1 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']
list2 = sorted(list1)
# sorted The function returns the sorted copy of the list without modifying the incoming list
# The design of functions should be like sorted Function, as far as possible without side effects
list3 = sorted(list1, reverse=True)
# adopt key The keyword parameter specifies to sort by string length instead of the default alphabetic order
list4 = sorted(list1, key=len)
print(list1)
print(list2)
print(list3)
print(list4)
# Send a sort message to the list object and sort directly on the list object
list1.sort(reverse=True)
print(list1)
if __name__ == '__main__':
main()We can also use the generative syntax of lists to create lists , The code is as follows .
import sys
def main():
f = [x for x in range(1, 10)]
print(f)
f = [x + y for x in 'ABCDE' for y in '1234567']
print(f)
# Create a list container using the list generation expression syntax
# After creating the list with this syntax, the elements are ready, so it takes a lot of memory space
f = [x ** 2 for x in range(1, 1000)]
print(sys.getsizeof(f)) # View the number of bytes of memory occupied by the object
print(f)
# Note that the following code creates not a list, but a generator object
# Data can be obtained through the generator, but it does not take up additional space to store data
# Every time you need data, you get the data through internal operation ( It takes extra time )
f = (x ** 2 for x in range(1, 1000))
print(sys.getsizeof(f)) # Compared with the generative generator, it does not occupy the space to store data
print(f)
for val in f:
print(val)
if __name__ == '__main__':
main() In addition to the generator syntax mentioned above ,Python There's another way to define generators , It is through yield Keyword transforms a normal function into a generator function . The following code demonstrates how to implement a build Fiborache series The generator . The so-called fiborache sequence can be passed through the following recursive To define :
$${\displaystyle F_{0}=0}$$
$${\displaystyle F_{1}=1}$$
$${\displaystyle F_{n}=F_{n-1}+F_{n-2}}({n}\geq{2})$$
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
yield a
def main():
for val in fib(20):
print(val)
if __name__ == '__main__':
main()边栏推荐
- Cvpr2022 𞓜 thin domain adaptation
- 一个简单而功能强大的开发者工具箱Box3.cc
- Record the range of data that MySQL update will lock
- Cvpr2022 | domaine compact adaptable
- 中国十大证券app排名 炒股开户安全吗
- CVPR 2022 - Interpretation of selected papers of meituan technical team
- Is industrial securities reliable? Is it safe to open a securities account?
- CVPR2022 | 可精簡域適應
- Stm32f1 and stm32cubeide programming examples -ws2812b full color LED driver (based on spi+dma)
- Esp32 series -- comparison of esp32 series
猜你喜欢

Keyword of ES mapping; Term query add keyword query; Change mapping keyword type

Two way combination of business and technology to build a bank data security management system

A brief introduction to the lexical analysis of PostgreSQL

Port conflict handling method for tongweb

Linux Installation cenos7 MySQL - 8.0.26

Don't underestimate the integral mall. It can play a great role

leetcode.12 --- 整数转罗马数字

Application of motion capture system in positioning and mapping of mobile robot in underground tunnel

postgresql之词法分析简介

Wide measuring range of jishili electrometer
随机推荐
Go language - use of goroutine coroutine
Bert-whitening 向量降维及使用
Wide measuring range of jishili electrometer
June training (day 23) - dictionary tree
Stm32f1 and stm32cubeide programming examples -ws2812b full color LED driver (based on spi+dma)
Which account of Dongfang fortune is safer and better
List of PostgreSQL
A series of problems caused by IPVS connection reuse in kubernetes
FPGA based analog I ² C protocol system design (Part 2)
Left hand code, right hand open source, part of the open source road
Laravel8 uses faker to call factory to fill data
[bitbear story collection] June MVP hero story | technology practice collision realm thinking
A common defect management tool - Zen, which teaches you from installation to using the handle
Don't underestimate the integral mall. It can play a great role
阿里OSS对象存储服务
兴业证券靠谱吗?开证券账户安全吗?
左手代码,右手开源,开源路上的一份子
Method after charging the idea plug-in material theme UI
Openinstall joins hands with the book chain to help channel data analysis and create the era of Book Networking
CVPR2022 | 可精簡域適應