奇怪的python系列,python如何做数组分割连接?
发布于 作者:苏南大叔 来源:程序如此灵动~
本文中苏南大叔来吐槽一下奇怪的python语言,其实,最奇怪的当属R语言。不过因为R语言和大家离得太远。所以,这里就先吐槽python语言吧。本文吐槽的地方是:数组截取,以及数组连接成字符串。

大家好,这里是苏南大叔的“程序如此灵动”博客,这里讲述一系列计算机代码的事情。本文测试环境:python@3.6.8。同样的写法,python里面的数组不叫array,叫list,而且操作极其诡异。
数组分割
_list = ["a","b","c","d","e"]
_list2 = _list[slice(2)] #["a","b"]
_list3 = _list[slice(1,2)] #["b"]
_list4 = _list[slice(3,5)] #["d","e"]
_list5 = _list[slice(9,10)] #[]
_list6 = _list[slice(4,10)] #["e"]做切片slice(),然后做list的位置信息。(下面的N和M都理解为自然意义上的数字排序,也就是说从1开始。)
- 切片slice(N),就返回第一个到第N个。
- 切片slice(N,M),就返回第N+1个到第M个。越界的话,就返回空。一部分越界的话,就返回不越界的。
php中的类似函数是array_slice,范例如下:
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // 返回 "c", "d" 和 "e"
$output = array_slice($input, -2, 1); // 返回 "d"
$output = array_slice($input, 0, 3); // 返回 "a", "b" 和 "c"对比就可以看出,这个python版本的slice是多么的不合常理了吧?函数放到了[]之中。
数组连接
数据连接,居然不是数组.join(字符串),而是字符串.join(数组)。
_list = ["a","b"]
# _str = _list.join(",") # AttributeError: 'list' object has no attribute 'join'
_str =",".join(_list) # a,b在试图数组.join(字符串)的时候,会收到报错信息:
AttributeError: 'list' object has no attribute 'join'在nodejs中,是用数组.join(字符串)的,php中是使用join(字符串,数组)的。
字符串去除两边空白
在php里面,使用trim(),ltrim(),rtrim()。
在python里面,函数名叫strip(),然后联动的函数叫做lstrip()和rstrip()。
_str=" a,b ".strip() # a,bnodejs里面没有内置的trim(),都是后来自定义的,暂不提。
相关链接
- https://newsn.net/say/pip-list-package-versions.html
- https://newsn.net/say/python-json.html
- https://newsn.net/say/php-implode.html
结束语
本文就是来吐槽python这些不合常理不按套路出牌的函数的,更多python吐槽,请参考苏南大叔的博客文章: