对MATLAB和Python中的序列运算进行横向比较

在 Python 中,有这样三种数据类型:元组、列表和字符串。而它们又可以统一称之为序列。学过 MATLAB 的童鞋看到这里可能会有种他乡遇故知的感觉,咦,MATLAB 里面不也是有这几种数据类型吗?的确,从定义到方法,这两者之间都有着太多的相同点,但在具体操作的过程中,还是有许多细节需要特别留意的。

何为序列

序列的主要功能是资格测试(Membership Test)(也就是 in 与 not in 表达式)和索引操作(Indexing Operations),它们能够允许我们直接获取序列中的特定项目。序列拥有一种切片(Slicing)运算符,它能够允许我们获得序列中的某段切片——也就是序列之中的一部分。

比较不同序列的声明方式

  • Python 版
# 声明一个列表型的变量
shoplist_l = ['apple', 'mango', 'carrot', 'banana']
# 声明一个元组型的变量
shoplist_c = ('apple', 'mango', 'carrot', 'banana')
# 声明一个字符串
name = 'swaroop'
print(shoplist_l)
print(shoplist_c)
print(name)

输出结果如下
这里写图片描述

  • MATLAB 版
% 声明一个列表型的变量
shoplist_l = ['apple', 'mango', 'carrot', 'banana'];
% 声明一个元组型的变量
shoplist_c = {'apple', 'mango', 'carrot', 'banana'};
% 声明一个字符串
name = 'swaroop';
shoplist_l
shoplist_c
name

输出结果如下
这里写图片描述

  • 总结
    Python 和 MATLAB 在定义元组时使用的符号是不同的。除此之外,Python 会对列表执行合并操作。

序列的索引使用

  • Python 版
# 索引或“下标(Subcription)”操作符 #
print('Item 0 is', shoplist_l[0])
print('Item 1 is', shoplist_l[1])
print('Item 2 is', shoplist_l[2])
print('Item 3 is', shoplist_l[3])

输出结果如下
这里写图片描述

  • MATLAB 版
disp(['Item 1 is', shoplist_c(1)])
disp(['Item 2 is', shoplist_c(2)])
disp(['Item 3 is', shoplist_c(3)])
disp(['Item 4 is', shoplist_c(4)])

输出结果如下
这里写图片描述

  • 总结
    Python 和 MATLAB 在使用索引时用来包含下标的符号是不同的,除此之外,Python 的下标从零开始,MATLAB 的下标从 1 开始。

负数对于序列的意义

  • Python 版
print('Item -1 is', shoplist_l[-1])
print('Item -2 is', shoplist_l[-2])

输出结果如下
这里写图片描述

  • MATLAB 版
shoplist_c(-1)

输出结果如下
这里写图片描述

  • 总结
    Python 的负下标从 - 1 开始从后往前对应元素,MATLAB 的下标只能为正整数。

序列的切片运算符

  • Python 版
print('Item 1 to 3 is', shoplist_l[1:3])
print('Item 2 to end is', shoplist_l[2:])
print('Item 2 to -1 is', shoplist_l[2:-1])
print('Item start to end is', shoplist_l[:])

输出结果如下
这里写图片描述

  • MATLAB 版
shoplist_c(1:3)
shoplist_c(2:end)
shoplist_c(2:-1)
shoplist_c(:)

输出结果如下
这里写图片描述

  • 总结
    Python 里 a:b 的含义是下标从 a 变化到 b-1,MATLAB 对应的含义是从 a 变化到 b。: 的含义对二者而言是一样的,即遍历所有元素。

注:序列定义以及 Python 部分的测试源代码来自《byte-of-python》。

猜你喜欢

转载自blog.csdn.net/jining11/article/details/81205832