2017.7.12 Python的6种内建序列及操作

数据结构是通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其他数据结构。

在Python中,最基本的数据结构是序列(sequence)。序列中的每个元素被分配一个序号--即元素的位置,也称为索引。第一个元素索引是0,第二个则是1,一次类推。

python包含6中内建的序列,即列表、元组、字符串、Unicode字符串、buffer对象和xrange对象。

通用序列操作:索引、分片、序列相加、乘法、成员资格、长度、最小值和最大值。

代码:

#-*- coding: UTF-8 -*-
number = [1,2,3,4,5,6,7,8,9,10]

#1.索引
#2.分片
print number[3]
print number[-1]
print number[-4:-1]
print number[1:3]
print number[:3]
print number[0:10:2]

#无输出

print number[10:0]
print number[10::-1]

#3.序列相加
print number + [11,12]

strs = "python"

print strs[1]
print strs[1:3]
print strs[-1]
print strs[-3:-1]
print strs[3:1:-1]
print strs[1:3:1]

print "hello"+strs

#4.乘法
print strs*4

#5.成员资格

print 't' in strs
print 'a' in strs

#6.长度、最小值和最大值

print len(number),len(strs)
print min(number),min(strs)
print max(number),max(strs)

输出结果:

4
10
[7, 8, 9]
[2, 3]
[1, 2, 3]
[1, 3, 5, 7, 9]
[]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
y
yt
n
ho
ht
yt
hellopython
pythonpythonpythonpython
True
False
10 6
1 h
10 y

一边喊着救命,一边享受沉沦。
原文地址:https://www.cnblogs.com/fast-walking/p/7153963.html