玩耍Python首页投稿(暂停使用,暂停投稿)

Python科学计算——Data Structures

2016-08-20  本文已影响284人  Lovingmylove521
The Zen of Python

为什么选择Python作为科学计算语言?

有关于MatlabPython哪个更适合作为科学计算语言的争论已久,之所以选择Python作为首选的科学计算语言,不仅仅是因为它免费,开源,有很多优秀的库和社区,基于 C 和 Fortran 开发有更好的表现,我想更多的是 Python 作为一种编程语言的简洁优雅深深吸引了我。Python 的设计原则有着禅宗的意味,输入import this就能在 Python 解释器中一窥玄机。

In [1]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
...

Data Structures in Python

Python 有四个内建的 Data Structures —— 列表 (List),元组 (Tuple),字典 (Dictionary) 以及集合 (Set),它们可以统称为容器 (container).

列表 (List)

Python 中最基本的数据结构是列表 (List)。 一个列表是一个有序的集合。

a = [1, 'abc', [2, 3]] # a 是一个 list
a[0] = 1 # 列表是从0开始索引的
a[1] = 'abc'

也可以用方括号来“切去”列表:

a[0:2] = ['abc', [2, 3]] # 索引a的前两个元素
a[-1:] = [2, 3] # 索引a的最后一个元素
a[-2:] = ['abc', [2, 3]] # 索引a的后两个元素
a[:-1] = [1, 'abc'] # 索引除了最后一个的其他元素
a = [1, 2, 3, 4, 5] # a 是一个 list

与列表先关的函数有很多,例如 compare( ),len( ),sum( ),min( ),max( ) ,sorted( ) 等,它们的具体用法如下:

In: sum(a)
Out: 15
In: max(a)
Out: 5
In: len(a)
Out: 5
a = [1, 3, 5, 3, 9, 7, 11, 13, 3, 5] # a 是一个 list

此外,作为对象,列表本身自带了很多实用的方法,如下所示:

In: a.append(1) # 在a的末尾加一个元素1
Out: a = [1, 3, 5, 3, 9, 7, 11, 13, 3, 5, 1]
In: a.count(3) # 统计a中3出现的次数
Out: 3
In: a.extend([2, 3]) # 将[2, 3]追加到a的末尾中
Out: a = [1, 3, 5, 3, 9, 7, 11, 13, 3, 5, 1, 2, 3]
In: a.insert(2, 1) # 将1插入a索引为2的位置
Out: a = [1, 3, 1, 5, 3, 9, 7, 11, 13, 3, 5, 1, 2, 3]
In: a.pop(3) # 移除a中索引为3的元素
Out: a = [1, 3, 1, 3, 9, 7, 11, 13, 3, 5, 1, 2, 3]
a = [1, 2, 3]
b = []
for i in a:
    b.append(i+2)
a = [1, 2, 3]
b = [i+2 for i in a] 

元组 (Tuple)

元组和列表有很多相似的地方,对列表的很多操作都可以对元组做,但元组和列表有两点不同的地方:

a = [1, 'abc', [2, 3], 'd'] # a 是一个 list
b = (1, 2, 3, 4, 5, 6, 7) # b 是一个 tuple
def sum_and_product(x, y):
      return (x + y), (x * y)
sp = sum_and_product(2, 3) # (5, 6)
s, p = sum_and_product(2, 3) # s = 5, p = 6

字典 (Dictionary)

Python 中的另一种基本数据结构是字典,它将值和键练习起来,让我们可以通过键快速找到对应的值:

empty_dict = {} # 创建一个空的dictionary
date = {'yesterday': 28, 'today': 29, 'tomorrow': 30} # 创建一个有内容的dictionary
date['yesterday'] # 28
date['the_day_after_tomorrow'] = 31
date_keys = date.keys() # 返回键的列表
date_values = date.values() # 返回值得列表
date_items = date.items() # (键,值)元组的列表
from collections import defaultdict
 word_counts = defaultdict(int)
for word in document:
      word_counts[word] += 1
from collections import Counter
c = Counter([0, 1, 2, 0]) # c = {0 : 2, 1 : 1, 2 : 1}

注:字典的键不可改变,尤其是不能将列表作为键,如果你需要一个多维的键,应该使用元组或设法将键转换成为字符串。

集合 (Set)

集合是 Python 中内置的另外一种数据结构。同数学上的集合概念类似,它与列表的主要区别在于:1. 它的元素是不重复的,且是无序的;2. 它不支持索引,一般通过花括号或者set()函数创建。

s = {1, 2, 3, 4, 2} # 2会被自动去重,得到{1,2,3,4}
s = set([1, 2, 3, 4, 2]) # 同样2被自动去重,将list转换为set
test_list = [1, 3, 2, 7, 8]
4 in test_list # False, 但需要检查每个元素
test_set = set(test_list)
4 in test_set # 非常快速的检查

注:我们使用 set 的频率要远低于 dictionary 和 list。

Stay hungry, Stay foolish. -- Steve Jobs

上一篇 下一篇

猜你喜欢

热点阅读