Python 数组/列表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 数组/列表相关的知识,希望对你有一定的参考价值。

范围取值

指定范围

names = ["","","","","","","",""]
print(names[1:4])#打印 一,二,三 左包括右不包括

从某位置取到末尾

names = ["","","","","","","",""]
print(names[1:])#打印 [‘一‘, ‘二‘, ‘三‘, ‘四‘, ‘五‘, ‘六‘, ‘七‘]

从某位置取到倒数第几个

names = ["","","","","","","",""]
print(names[1:-3])#打印 [‘一‘, ‘二‘, ‘三‘, ‘四‘]

跳着取值

names = ["","","","","","","",""]
print(names[0::1])#打印[‘零‘, ‘一‘, ‘二‘, ‘三‘, ‘四‘, ‘五‘, ‘六‘, ‘七‘]  //从头到尾一个一个取
print(names[0:-1:2])#打印[‘零‘, ‘二‘, ‘四‘, ‘六‘]  //从头到倒数第二个,跳着一个一个取
print(names[0::3])#打印[‘零‘, ‘三‘, ‘六‘]    //从头到尾跳着两个取

倒数取值

names = ["","","","","","","",""]
print(names[5::-1])#打印[‘五‘, ‘四‘, ‘三‘, ‘二‘, ‘一‘, ‘零‘]    //第5个元素到第1个元素,倒着一个一个取
print(names[6:2:-2])#打印[‘六‘, ‘四‘]    //第6个元素到第2个元素,倒着跳一个一个取
print(names[-1:0:-2]

 

以上是关于Python 数组/列表的主要内容,如果未能解决你的问题,请参考以下文章

如何使列表视图出现在片段中?

Python代码阅读(第26篇):将列表映射成字典

Python代码阅读(第25篇):将多行字符串拆分成列表

Python代码阅读(第40篇):通过两个列表生成字典

Python代码阅读(第13篇):检测列表中的元素是否都一样

30 段 Python 实用代码