Lists

动态数组,可以存储不同数据类型

>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]

和string一样,支持索引,+,*

>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']

和string不同,list的元素是可变的

>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]

可以给范围索引负值,另类的插入、删除操作

>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]

len()内置函数用来测量长度

>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4

多维数组

>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2

appen函数在数组末尾添加元素

>>> p[1].append('xtra')
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']

 in操作符测试包含关系

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):while True:ok = input(prompt)if ok in ('y', 'ye', 'yes'):return Trueif ok in ('n', 'no', 'nop', 'nope'):return Falseretries = retries - 1if retries < 0:raise IOError('refusenik user')print(complaint)

 常用函数

list.append(x)

Add an item to the end of the list. Equivalent to a[len(a):] = [x].

list.extend(L)

Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.

list.insert(ix)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)

Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.index(x)

Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x)

Return the number of times x appears in the list.

list.sort()

Sort the items of the list in place.

list.reverse()

Reverse the elements of the list in place.

 

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]

list做栈用

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

list做队列用

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

List Comprehensions   可读性更高,更简洁的集合初始化

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]#等价于
squares = [x**2 for x in range(10)]
>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]#等价于
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

 

>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]File "<stdin>", line 1, in ?[x, x**2 for x in range(6)]^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

del   按索引删除

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

del 也可以用来删除变量

>>> del a

 

转载于:https://www.cnblogs.com/wangjixianyun/archive/2012/12/27/2836601.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/274409.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

学习 axios 源码整体架构,打造属于自己的请求库

前言这是学习源码整体架构系列第六篇。整体架构这词语好像有点大&#xff0c;姑且就算是源码整体结构吧&#xff0c;主要就是学习是代码整体结构&#xff0c;不深究其他不是主线的具体函数的实现。本篇文章学习的是实际仓库的代码。学习源码整体架构系列文章如下&#xff1a;1.…

404 错误页面_如何设计404错误页面,以使用户留在您的网站上

404 错误页面重点 (Top highlight)网站设计 (Website Design) There is a thin line between engaging and enraging when it comes to a site’s 404 error page. They are the most neglected of any website page. The main reason being, visitors are not supposed to end…

宏定义学习

【1】宏定义怎么理解&#xff1f; 关于宏定义&#xff0c;把握住本质&#xff1a;仅仅是一种字符替换&#xff0c;而且是在预处理之前就进行。 【2】宏定义可以包括分号吗&#xff1f; 可以&#xff0c;示例代码如下&#xff1a; 1 #include<iostream>2 using namespace…

学习 koa 源码的整体架构,浅析koa洋葱模型原理和co原理

前言这是学习源码整体架构系列第七篇。整体架构这词语好像有点大&#xff0c;姑且就算是源码整体结构吧&#xff0c;主要就是学习是代码整体结构&#xff0c;不深究其他不是主线的具体函数的实现。本篇文章学习的是实际仓库的代码。学习源码整体架构系列文章如下&#xff1a;1.…

公网对讲机修改对讲机程序_更少的对讲机,对讲机-更多专心,专心

公网对讲机修改对讲机程序重点 (Top highlight)I often like to put a stick into the bike wheel of the UX industry as it’s strolling along feeling proud of itself. I believe — strongly — that as designers we should primarily be doers not talkers.我经常喜欢在…

spring配置文件-------通配符

<!-- 这里一定要注意是使用spring的mappingLocations属性进行通配的 --> <property name"mappingLocations"> <list> <value>classpath:/com/model/domain/*.hbm.xml</value> </list> </proper…

若川知乎问答:2年前端经验,做的项目没什么技术含量,怎么办?

知乎问答&#xff1a;做了两年前端开发&#xff0c;平时就是拿 Vue 写写页面和组件&#xff0c;简历的项目经历应该怎么写得好看&#xff1f;以下是我的回答&#xff0c;阅读量5000&#xff0c;所以发布到公众号申明原创。题主说的2年经验做的东西没什么技术含量&#xff0c;应…

ui设计基础_我不知道的UI设计的9个重要基础

ui设计基础重点 (Top highlight)After listening to Craig Federighi’s talk on how to be a better software engineer I was sold on the idea that it is super important for a software engineer to learn the basic principles of software design.听了克雷格费德里希(C…

Ubuntu下修改file descriptor

要修改Ubuntu下的file descriptor的话&#xff0c;请参照一下步骤。&#xff08;1&#xff09;修改limits.conf  $sudo vi /etc/security/limits.conf  增加一行  *  -  nofile  10000&#xff08;2&#xff09;修改 common-session  $ sudo vi/etc/pam.d/common…

C# 多线程控制 通讯 和切换

一.多线程的概念   Windows是一个多任务的系统&#xff0c;如果你使用的是windows 2000及其以上版本&#xff0c;你可以通过任务管理器查看当前系统运行的程序和进程。什么是进程呢&#xff1f;当一个程序开始运行时&#xff0c;它就是一个进程&#xff0c;进程所指包括运行中…

vue路由匹配实现包容性_包容性设计:面向老年用户的数字平等

vue路由匹配实现包容性In Covid world, a lot of older users are getting online for the first time or using technology more than they previously had. For some, help may be needed.在Covid世界中&#xff0c;许多年长用户首次上网或使用的技术比以前更多。 对于某些人…

IPhone开发 用子类搞定不同的设备(iphone和ipad)

用子类搞定不同的设备 因为要判断我们的程序正运行在哪个设备上&#xff0c;所以&#xff0c;我们的代码有些混乱了&#xff0c;IF来ELSE去的&#xff0c;记住&#xff0c;将来你花在维护代码上的时间要比花在写代码上的时间多&#xff0c;如果你的项目比较大&#xff0c;且IF语…

见证开户_见证中的发现

见证开户Each time we pick up a new video game, we’re faced with the same dilemma: “How do I play this game?” Most games now feature tutorials, which can range from the innocuous — gently introducing each mechanic at a time through natural gameplay — …

使用JXL组件操作Excel和导出文件

使用JXL组件操作Excel和导出文件 原文链接&#xff1a;http://tianweili.github.io/blog/2015/01/29/use-jxl-produce-excel/ 前言&#xff1a;这段时间参与的项目要求做几张Excel报表&#xff0c;由于项目框架使用了jxl组件&#xff0c;所以把jxl组件的详细用法归纳总结一下。…

facebook有哪些信息_关于Facebook表情表情符号的所有信息

facebook有哪些信息Ever since worldwide lockdown and restriction on travel have been imposed, platforms like #Facebook, #Instagram, #Zoom, #GoogleDuo, & #Whatsapp have become more important than ever to connect with your loved ones (apart from the sourc…

M2总结报告

团队成员 李嘉良 http://home.cnblogs.com/u/daisuke/ 王熹 http://home.cnblogs.com/u/vvnx/ 王冬 http://home.cnblogs.com/u/darewin/ 王泓洋 http://home.cnblogs.com/u/fiverice/ 刘明 http://home.cnblogs.com/u/liumingbuaa/ 由之望 http://www.cnbl…

react动画库_React 2020动画库

react动画库Animations are important in instances like page transitions, scroll events, entering and exiting components, and events that the user should be alerted to.动画在诸如页面过渡&#xff0c;滚动事件&#xff0c;进入和退出组件以及应提醒用户的事件之类的…

Weather

public class WeatherModel { #region 定义成员变量 private string _temperature ""; private string _weather ""; private string _wind ""; private string _city ""; private …

线框模型_进行计划之前:线框和模型

线框模型Before we start developing something, we need a plan about what we’re doing and what is the expected result from the project. Same as developing a website, we need to create a mockup before we start developing (coding) because it will cost so much…

撰写论文时word使用技巧(转)

------------------------------------- 1. Word2007 的表格自定义格式额度功能是很实用的&#xff0c;比如论文中需要经常插入表格的话&#xff0c; 可以在“表格设计”那里“修改表格样式”一次性把默认的表格样式设置为三线表&#xff0c;这样&#xff0c; 你以后每次插入的…