GoodZhang在学Python(八)--基本数据结构

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhdl11/article/details/38757635

Python中有三种内建的基本数据结构:

  • 列表 list
  • 元组 tuple
  • 字典 dictionary

list 列表

是处理有序项目的数据结构,基本格式为: list = ['aaa', 'bbb', 'ccc']
可以对列表中的项目进行删除、添加、搜索等操作。

通过下面的例子体会一下列表的基本操作:

__author__ = 'zWX231671'

nbaplayer = ['Kobe', 'James', 'Yao', 'RayAllen', 'Garnet']

print('I like', len(nbaplayer), 'players', end=',')
print('they are:')
# 遍历list
for player in nbaplayer:
    print(player, end='  ')

print('\nI like Wade too, so I must add Wade into the list')
nbaplayer.append('Wade')
print('now the list is:', nbaplayer)
nbaplayer.sort()
print('the sorted list is ', nbaplayer)

retire = nbaplayer[len(nbaplayer)-1]
del nbaplayer[len(nbaplayer)-1]
print('expect the retired player, the list is ',nbaplayer)
输出结果为:


另外,python列表常用的操作还有:

  • list.append(x):在列表list的尾部追加一个元素,类型可以为列表允许的数据结构
  • list.extend(L):在list的尾部累加列表L,等价于list + L
  • list.insert(i,x):在列表给定的位置上插入一个元素,当i > len(list)时,等价list.append(x)
  • list.remove(x):删除列表中第一次出现的元素x,如果列表中没有x则会报异常
  • list.pop([ i ]):删除给定位置上 i 的元素并返回,如果没有指定则删除最后一个元素并返回
  • list.index(x):返回元素x第一次出现位置的索引,如果列表中没有x元素则报异常
  • list.count(x):返回列表中x出现的次数
  • list.sort():对列表的元素进行排序,其默认排序规则为cmp(x , y)
  • list.reverse():颠倒元素的顺序

tuple 元组

元组与列表很像,不过元组是不可改变的,一般用于存储一些固定不变的值,基本格式为: tuple = ('aaa', 'bbb', 'ccc')
例子:
__author__ = 'zWX231671'

west = ('okc', 'lakers', 'rocket', 'wolf')
east = ('heat', 'bulls', '76er', 'nicks')

total = len(east) + len(west)
print('the number of team is ', total)

print('west teams are ', west)
print('east teams are ', east)

allstar = ('nets', west, east)
print(allstar[1][0])
# 列表之中的列表时不会丢失的,同样元组之中的数组也是不会丢失的,只是使用另外一个对象,存储这一个对象罢了
print(west)
输出结果:


dictionary 字典

字典是使用键值对方式来存储数据的,键--值一一对应,键是唯一的,只能使用不可变的对象来作键。
键值之间通过冒号分隔,不同的键值对之间通过逗号分隔,整体全部放进大括号中,基本格式: dic = {key1 : value1, key2 : value2, key3 : value3}
例子:
__author__ = 'zWX231671'

dic = {
    'lile' : '18253161970',
    'andong' : '18253161349',
    'zhonghuan' : '18253164491'
}

print('the phone of lile is %s' % dic['lile'])
dic['hanyuqiang'] = '18253162906'
dic['liuqiushan'] = '18253163951'
dic['zhangdianlei'] = '18253163738'
# 可以看出,dic中的数据果断是无序的
print('this dictionary has %d records' % len(dic), 'they are:\n', dic)
# 删除操作
del dic['zhangdianlei']
# 遍历
for name, phone in dic.items():
    print('we hava %s,phone is %s' % (name, phone))
输出结果:





猜你喜欢

转载自blog.csdn.net/zhdl11/article/details/38757635