创建
基本相同
js
var person = ['xiaohong','wangwei','liudehua'];
python
person=['xiaohong','wangwei','liudehua']
访问元素
基本相同
js
person[0] //xiaohong
python
>>> person[0]
'xiaohong'
切片
这块不一样,js用slice函数,python没用这个同样完成切片,此外,js里面是逗号,python语法里是冒号。一个是括号,一个是中括号。
js
person.slice(0,2) // ["xiaohong", "wangwei"]
python
>>> person[0:2]
['xiaohong', 'wangwei']
获取元素索引
一个明明为indexof,一个命名为index,半斤八两
js
person.indexOf('xiaohong') //0
python
>>> person.index('xiaohong')
0
向末尾添加新元素
js起名叫push,python起名叫append
js
person.push('daniu') //4
person // ["xiaohong", "wangwei", "liudehua", "daniu"]
python
>>> person.append('daniu')
>>> person
['xiaohong', 'wangwei', 'liudehua', 'daniu']
删除元素
js pop删除最后一个,shift删除第一个。python指定索引随便删,也有pop,没有shift
js
person.pop()
"daniu"
person
(3) ["xiaohong", "wangwei", "liudehua"]
person.shift()
"xiaohong"
person
(2) ["wangwei", "liudehua"]
python
>>> person.pop()
'daniu'
>>> person
['wangwei', 'liudehua']
>>> del(person[0])
>>> person
['wangwei', 'liudehua', 'daniu']
排序
基本一样,都是sort方法
js
person.sort()
(3) ["daniu", "liudehua", "wangwei"]
python
>>> person.sort()
>>> person
['daniu', 'liudehua', 'wangwei']
反转
基本一样
js
person.reverse()
(3) ["wangwei", "liudehua", "daniu"]
python
>>> person.reverse()
>>> person
['wangwei', 'liudehua', 'daniu']
连接数组
js
js用contact,python用extend
var arr = ['A', 'B', 'C']
var added=arr.concat([1,2,3])
added //(6) ["A", "B", "C", 1, 2, 3]
python
>>> arr = ['A', 'B', 'C']
>>> arr.extend([1,2,3])
>>> arr
['A', 'B', 'C', 1, 2, 3]
join
应该说python这么写略奇葩
js
var arr = ['A', 'B', 'C', 1, 2, 3]
arr.join('-')
"A-B-C-1-2-3"
python
>>> arr = ['A', 'B', 'C']
>>> '-'.join(arr)
'A-B-C'
元组
元组是不可变的,js无元组,如果需要,大概会有什么变通之法?
js
无
python
>>> s=(1,2,3)
>>> s.pop()
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
s.pop()
AttributeError: 'tuple' object has no attribute 'pop'
字典
js
无但是可以用数组变通实现
python
>>> phonebook = {'Alice':'2341','Beth':'9102','Ceil':'3258'}
>>> phonebook
{'Beth': '9102', 'Ceil': '3258', 'Alice': '2341'}
总结
可以看出python为了简化写法整了不少东西,比如同样是切片,python就比js少码很多字。