Python 为我们提供了三种常用数据结构,列表(Lists),字典(Dictionary),元组(Tuple)。为何要了解三种数据结构,这事的意义就不必多说了,让我们开始了解这三种最重要的数据结构吧。

1、列表

好学:列表Lists有什么特点?
(按捺不住激动心情地想先说Python)
大佬:列表就像高级链表(有序,动态,可同时存放不同类型的数据)。

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.(翻译:python经常在使用列表(工具)来处理一些复杂的数据。在python中,用一对方括号来表示列表。列表除了能放相同类型的数据,也能放不同的数据。也就是说列表不限制数据类型。)
而java,没有列表这个概念。

好学:麻烦给我一份列表使用方法说明书吧!
大佬:嗯,往下看。都是些常见的操作
1.1基础操作

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

Like strings (and all other built-in sequence type), lists can be indexed and sliced(切割,划分):

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

All slice operations return a new list containing the requested elements(返回你想要的样子). This means that the following slice returns a new (shallow) copy of the list:

>>> squares[:]
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content:

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

You can also add new items at the end of the list, by using the append() method (we will see more about methods later):

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely(完全清除):

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

The built-in function len() also applies to lists:

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

It is possible to nest (窝,套件)lists (create lists containing other lists), for example:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

1.2 More on Lists
The list data type has some more methods. Here are all of the methods of list objects:

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

list.extend(iterable)
Extend the list by appending all the items from the iterable(能迭代的). Equivalent to a[len(a):] = iterable.

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.clear()
Remove all items from the list. Equivalent to del a[:].

list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

list.count(x)
Return the number of times x appears in the list.

list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse()
Reverse(反转,颠倒) the elements of the list in place.

list.copy()
Return a shallow copy of the list. Equivalent to a[:].

An example that uses most of the list methods:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. [1] This is a design principle for all mutable data structures in Python.

2、字典

好学:python列表既是动态的,还能当做栈,队列来用,那字典呢?
大佬:有时候用数字索引取值很麻烦,倒不如用key取值来的直观(就像是hashmap,图这种数据结构)
Another useful data type built into(内建) Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences(不像是连续的), which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable(不可变的) type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable (可变的)object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified (改进,改良)in place using index assignments, slice assignments, or methods like append() and extend().

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.

Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). [2] To check whether a single key is in the dictionary, use the in keyword.
Here is a small example using a dictionar

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel

False dict() constructor builds dictionaries directly from sequences of key-value pairs:

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify (指定)pairs using keyword arguments:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

Looping Techniques(字典的遍历)
When looping through dictionaries, the key and corresponding value(相应的值) can be retrieved(取回)at the same time using the items() method.

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():print(k, v)gallahad the pure
robin the brave

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]

3、元组

好问:列表,字典都有了,这元组一般也用不上呀?!
大佬:列表是可变的有序列表,元组是不可变的有序列表,唯一且最重要的区别在于tuple更安全。
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.

A tuple consists of a number of values separated by commas, for instance:

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks ( 怪癖; 奇事);
)to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:

>>>
>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

The statement t = 12345, 54321, ‘hello!’ is an example of tuple packing: the values 12345, 54321 and ‘hello!’ are packed together in a tuple.

Python三种数据结构相关推荐

  1. 汇总python三种数据结构list,set,dict的常见操作

    文章目录 前言 list set dict 前言 这3个东西太常用,必须熟练掌握. list 功能 操作 去重 set(a) 排序 a.sort() 或者a=sorted(a) 插入 a.insert ...

  2. Python 三种读文件方法read(), readline(), readlines()及去掉换行符\n

    Python 三种读文件方法read(), readline(), readlines()及去掉换行符\n 首先, 让我们看下数据demo.txt, 就两行数据. 35durant teamGSW 1 ...

  3. python三种注释方法

    python三种注释方法 方式1: 单行注释:shift + #(在代码的最前面输入,非选中代码进行注释) 多行注释:同单行一样在每一行的前面输入shift + #(较麻烦了) 方式2: 单行和多行一 ...

  4. python三种方法实现阶乘

    # python三种方法实现阶乘 # while循环实现阶乘 def fact(n):if n == 0:return 1 # 0 的阶乘为 1elif n < 0:return '负数没有阶乘 ...

  5. python三种保留两位小数的方法

    python三种保留两位小数方法汇总 1.'%.2f'%f 该方法会进行四舍五入 代码如下所示: f = 2.3456789print('%.2f'%f) print('%.3f'%f) print( ...

  6. python 三种聚类算法(K-means,AGNES,DBScan)

    python实现鸢尾花三种聚类算法(K-means,AGNES,DBScan) 更新时间:2019年06月27日 14:44:44   作者:weixin_42134141 这篇文章主要介绍了pyth ...

  7. python中if brthon环境安装包_Ant、Gradle、Python三种打包方式的介绍

    今天谈一下Androdi三种打包方式,Ant.Gradle.Python. 当然最开始打包用Ant 很方便,后来转Studio开发,自带很多Gradle插件就用了它,然后随着打包数量越多,打包时间成了 ...

  8. python三种变量方式_python2.x 3种变量形式调用

    python 变量使用 raw_input 2.x = input 3.x 第一种name = input("name:") age = input("age:" ...

  9. python三种数据类型_Python零基础入门学习02:Python基本数据类型:数字类型

    注 :本文所有代码均经过Python 3.7实际运行检验,保证其严谨性. Python学习 Python有三种不同的数字类型:整数(int),浮点数(float)和复数(complex). 值得注意的 ...

最新文章

  1. 一个类可以实现多个接口但是只能实现一个类
  2. chrome浏览器无法上网_浏览器无法上网
  3. JVM学习笔记之-运行时数据区概述及线程概述,程序计数器(PC寄存器),虚拟机栈(栈,局部变量表,操作数栈,动态连接,方法调用,方法返回地址等),本地方法接口,本地方法栈
  4. 面试官:为什么 HashMap 的加载因子是0.75?
  5. 关于错误Resource interpreted as Script but transferred with MIME type text_html
  6. 动感灯箱制作流程培训_2000多年的灯箱发展史,你知道多少?
  7. oracle监听系统账号,linux 下 Oracle 监控sysdba用户登陆
  8. ios加载本地html懒加载图片方案,IOS开发中加载大量网络图片优化方法
  9. 吴恩达神经网络和深度学习-学习笔记-15-局部最优
  10. maven工具使用json-lib时,JSONArray.fromObject()不能执行的解决方案
  11. 一年级abb式词语并造句_ABB式词语如何活学活用,家长都收藏了!
  12. 计算机导论论文含图,计算机导论(论文).doc
  13. 从月薪3000到月薪过万:做什么工作才能过上想要的生活
  14. 中职学校计算机专业的论文,浅谈中职计算机专业教学改革思考论文
  15. 笨拙的手指 代码优化版
  16. B+tree演示地址
  17. js截取字符串的后几位数
  18. 用 CAReplicatorLayer 创建动画
  19. 自强不息nbsp;回报社会nbsp;——记残疾人电脑…
  20. Luogu P1502 窗口的星星 (扫描线)

热门文章

  1. Spring boot集成freemarker导出excel
  2. 软件License设计
  3. 用ILDasm.exe深入理解委托 ()
  4. 我的家装日记16(完结篇)
  5. VDMA学习(一)pg020总结
  6. 编译型语言和脚本型语言的区别
  7. 58同城徐振华:58同城分布式存储架构
  8. 2021年高压电工考试资料及高压电工考试试卷
  9. 动态配置定时任务(Spring Boot + quartz 的整合)
  10. tomcat升级到10后启动报错