Home Backend Development Python Tutorial python开发之list操作实例分析

python开发之list操作实例分析

Jun 10, 2016 pm 03:06 PM
list python

本文实例分析了python开发之list操作。分享给大家供大家参考,具体如下:

对python中list的操作,大家可以参考《Python list操作用法总结》

以下是我个人的笔记:

#python list
'''
  创建list有很多方法:
  1.使用一对方括号创建一个空的list:[]
  2.使用一对方括号,用','隔开里面的元素:[a, b, c], [a]
  3.Using a list comprehension:[x for x in iterable]
  4.Using the type constructor:list() or list(iterable)
'''
def create_empty_list():
  '''Using a pair of square brackets to denote the empty list: [].'''
  return []
def create_common_list():
  '''Using square brackets, separating items with commas: [a], [a, b, c].'''
  return ['a', 'b', 'c', 1, 3, 5]
def create_common_list2():
  '''Using a list comprehension: [x for x in iterable].'''
  return [x for x in range(1, 10)]
def str_to_list(s):
  '''Using a string to convert list'''
  if s != None:
    return list(s)
  else:
    return []
def main():
  test_listA = create_empty_list()
  print(test_listA)
  print('#' * 50)
  test_listB = create_common_list()
  print(test_listB)
  print('#' * 50)
  test_listC = create_common_list2()
  print(test_listC)
  print('#' * 50)
  test_str = 'i want to talk about this problem!'
  test_listD = str_to_list(test_str)
  print(test_listD)
if __name__ == '__main__':
  main()

Copy after login

运行效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
[]
##################################################
['a', 'b', 'c', 1, 3, 5]
##################################################
[1, 2, 3, 4, 5, 6, 7, 8, 9]
##################################################
['i', ' ', 'w', 'a', 'n', 't', ' ', 't', 'o', ' ', 't', 'a', 'l', 'k', ' ', 'a', 'b', 'o', 'u', 't', ' ', 't', 'h', 'i', 's', ' ', 'p', 'r', 'o', 'b', 'l', 'e', 'm', '!']
>>> 

Copy after login

下面有更多的demo:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> counter = 100
>>> miles = 1000.0
>>> name = "hongten"
>>> numberA,numberB,nameC = 1,2,"Hongten"
>>> list = [counter,miles,name,numberA,numberB,nameC]
>>> print(list)
[100, 1000.0, 'hongten', 1, 2, 'Hongten']
>>> #这是注释部分,注释用"#"开始
>>> for element in list:
  print(element)
100
1000.0
hongten
1
2
Hongten
>>> #上面是遍历列表list
>>> print(list[0]) #获取列表list里面的第一个元素值
100
>>> print(list[-1]) #获取列表list里面的最后一个元素值
Hongten
>>> print(len(list)) #用len(list)获取list列表的长度
6
>>> num_inc_list = range(10) #产生一个数值递增的列表
>>> print(num_inc_list)
range(0, 10)
>>> for inc_list in num_inc_list:
  print(inc_list)
0
1
2
3
4
5
6
7
8
9
>>> #从这里我们可以看到range(10)是产生了一个从0开始到9的一个数值递增列表
>>> initial_value = 10
>>> list_length = 5
>>> myList = [initial_value for i in range(10)]
>>> print(myList)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> list_length = 2
>>> myList = myList * list_length
>>> print(myList)
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> print(len(myList))
20
>>> #上面是用一个固定值initial_value去初始化一个列表myList
>>> #同时用myList = myList * list_length去复制myList
>>> #下面再看看复制的效果
>>> copyList = [1,2,3,"hongten"]
>>> copyList = copyList * list_length
>>> print(len(copyList))
8
>>> for cl in copyList:
  print(cl)
1
2
3
hongten
1
2
3
hongten
>>> #下面我们来仔细研究一下python里面的list
>>> #在一个list中可以包含不同类型的元素,这个和ActionScript 3.0(AS3.0)中的数组类似
>>> test_list = ["hello",1,2,"world",4,5,"hongten"]
>>> print(len(test_list))
7
>>> print(test_list[0]) # 打印test_list
hello
>>> #打印test_list中的第一元素
>>> print(test_list[-1]) #打印test_list中最后一个元素
hongten
>>> print(test_list[-len]) #打印第一个元素
Traceback (most recent call last):
 File "<pyshell#44>", line 1, in <module>
  print(test_list[-len]) #打印第一个元素
TypeError: bad operand type for unary -: 'builtin_function_or_method'
>>> print(test_list[-len(test_list)]) #打印第一个元素
hello
>>> print(test_list[len(test_list) - 1]) #打印最后一个元素
hongten
>>> test_list.append(6) #向列表中追加一个元素
>>> print(test_list[-1])
6
>>> test_list.insert(1,0)
>>> print(test_list)
['hello', 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> #上面的操作是向列表test_list的小标为1的地方插入元素0
>>> test_list.insert(1,0)
>>> print(test_list)
['hello', 0, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.insert(2,1)
>>> print(test_list)
['hello', 0, 1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> print(test_list.pop(0)) #返回最后一个元素,并从test_list中删除之
hello
>>> print(test_list)
[0, 1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> print(test_list.pop(2)) #上面的注释有错误,pop(index)的操作是返回数组下标为index的元素,并从列表中删除之
0
>>> print(test_list)
[0, 1, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.remove(1)
>>> print(test_list)
[0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> #remove(1)表示的是删除第一次出现的元素1
>>> test_list.insert(0,1)
>>> print(test_list)
[1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.remove(1)
>>> print(test_list)
[0, 1, 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.insert(2,"hongten")
>>> print(test_list)
[0, 1, 'hongten', 2, 'world', 4, 5, 'hongten', 6]
>>> test_list.count("hongten")
2
>>> #count(var)是统计var元素在列表中出现的个数
>>> test_list.count("foo")
0
>>> test_list_extend = ["a","b","c"]
>>> test_list.extend(test_list_extend)
>>> print(test_list)
[0, 1, 'hongten', 2, 'world', 4, 5, 'hongten', 6, 'a', 'b', 'c']
>>> #使用extend(list)作用是追加一个list到源list上面
>>> print(test_list.sort())
Traceback (most recent call last):
 File "<pyshell#76>", line 1, in <module>
  print(test_list.sort())
TypeError: unorderable types: str() < int()
>>> test_list_extend.append("h")
>>> test_lsit_extend.append("e")
Traceback (most recent call last):
 File "<pyshell#78>", line 1, in <module>
  test_lsit_extend.append("e")
NameError: name 'test_lsit_extend' is not defined
>>> list_a = ["e","z","o","r"]
>>> list_a.extend(test_list_extend)
>>> print(list_a)
['e', 'z', 'o', 'r', 'a', 'b', 'c', 'h']
>>> print(list_a.sort()) #对list_a列表进行排序
None
>>> #不知道为什么以上排序都有报错......
>>> list_b = [1,3,5,2,6,4]
>>> print(list_b.sort())
None
>>> print(sort(list_b))
Traceback (most recent call last):
 File "<pyshell#86>", line 1, in <module>
  print(sort(list_b))
NameError: name 'sort' is not defined
>>> #不去管排序问题了,先看看删除操作吧!!!!!
>>> print(list_b)
[1, 2, 3, 4, 5, 6]
>>> print(del list_b[1])
SyntaxError: invalid syntax
>>> del list_b[1]
>>> print(list_b)
[1, 3, 4, 5, 6]
>>> del list_b[0,2]
Traceback (most recent call last):
 File "<pyshell#92>", line 1, in <module>
  del list_b[0,2]
TypeError: list indices must be integers, not tuple
>>> del list_b[0:2]
>>> print(list_b)
[4, 5, 6]
>>> #del list[index]删除下标为index的元素,del list[start:end]删除从start下标开始到end下标结束的元素
>>> del list_b[10]
Traceback (most recent call last):
 File "<pyshell#96>", line 1, in <module>
  del list_b[10]
IndexError: list assignment index out of range
>>> #如果我们删除的下标超出了列表的长度范围,就会报错啦!!!!!
>>> ##########################################################################
>>> list_c = range(5);
>>> for c in list_c:
  print(c)
0
1
2
3
4
>>> list_d = list_c
>>> for d in list_d:
  print(d)
0
1
2
3
4
>>> #上面是列表的复制
>>> list_d[2] = 23
Traceback (most recent call last):
 File "<pyshell#108>", line 1, in <module>
  list_d[2] = 23
TypeError: 'range' object does not support item assignment
>>> list_e = [1,2,3,4,5]
>>> list_f = list_e
>>> list_f[2] = 234
>>> print(list_e)
[1, 2, 234, 4, 5]
>>> #从这里我们可以知道,list_f复制了list_e,list_f是对list_e的一个引用,
>>> #他们共同指向一个对象:[1,2,3,4,5],当我们视图修改list_f[2]的值的时候,
>>> #list_f所指向的对象的行为发生了变化,即元素值发生了变化,但是他们的引用是没有
>>> #发生变化的。所以list_e[2] = 234也是在情理之中。
>>> #######################################################################
>>> list_i = list_e[:]
>>> print(list_i)
[1, 2, 234, 4, 5]
>>> print(list_e)
[1, 2, 234, 4, 5]
>>> list_i[2] = 3
>>> print(list_e)
[1, 2, 234, 4, 5]
>>> print(list_i)
[1, 2, 3, 4, 5]
>>> #上面是进行了列表的克隆操作,即拷贝了另一个列表,这样的操作,会创造出新的一个列表对象
>>> #使得list_i和list_e指向不同的对象,就有着不同的引用,所以当list_i[2] = 3的时候,
>>> #list_e[2]还是等于234,即不变
>>>

Copy after login

希望本文所述对大家Python程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

Solutions to the service that cannot be started after MySQL installation Solutions to the service that cannot be started after MySQL installation Apr 08, 2025 am 11:18 AM

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

See all articles