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(i,?x)

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.pswp.cn/news/274409.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/274409.shtml
英文地址,請注明出處:http://en.pswp.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; 你以后每次插入的…