jack0he的个人博客分享 http://blog.sciencenet.cn/u/jack0he

博文

Python-note-7-data structure-lists

已有 2327 次阅读 2017-4-12 02:21 |个人分类:Python 笔记|系统分类:科研笔记

Data structures:

1, numbers

2, strings,

3, lists,

4, tuples,

5, dictionaries


This part concerns the list data type.


A list is a vector contains multiple values, including numbers, strings and/or lists. Differing from Matlab in which the elements are bracketed by (), Python brackets the ordered elements by []. In the list of Python, each element is seperated by ','. In order to find an element of a list, the concept index is proposed. The number of index starts from 0.


Example-1

animal=['cat','dog','fish','elephant']

animal[0]

---

outPut

'cat'


NB-1: if the value of the index equals or is larger than the total number of elements of a list, it will cause IndexError.

animal[5]

---

outPut

Traceback (most recent call last):

 File "<pyshell#19>", line 1, in <module>

   animal[5]

IndexError: list index out of range

NB-2: The index can be negative. In that cases, the value -1 refers to the last index in a list.

NB-3: A slice can get several values of a list. It starts from the first index and ends but excludes the second index.

Example:

animal[0:2]

['cat','dog']

animal[0:-1]

['cat','dog','fish']

animal[1:]

['dog','fish','elephant']

animal[:]

['cat','dog','fish','elephant']


NB-4: list concatenation and list replication

[1,2,3]+['cat','dog','fish','elephant']

[1,2,3,'cat','dog','fish','elephant']

['cat','dog','fish','elephant']*3=['cat','dog','fish','elephant','cat','dog','fish','elephant','cat','dog','fish','elephant']


NB-5: remove values from a list

Example:

animal=['cat','dog','fish','elephant']

del animal[2]

animal

---

outPut

['cat','dog','elephant']



https://wap.sciencenet.cn/blog-850613-1048320.html

上一篇:Python-Note-6-Global and local variables
下一篇:Python-Note-8-data structure-lists (continue)
收藏 IP: 80.101.95.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-26 00:56

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部