python基础知识:数据结构的学习

Posted 拉努斯石

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础知识:数据结构的学习相关的知识,希望对你有一定的参考价值。


python的数据结构有:列表、元组、字典

列表:
作用:处理 有序 项目的数据结构
list=["a",‘b‘,‘v‘,‘d‘]
# 打印长度
print(len(list))
# 循环打印
for i in list:
print i
# 在序列最后插入数据
list.append("5")
for i in list:
print i
print(list[0])
# 删除序列中的某个元素
del list[0]
print(list[0])
# 对列表进行排序
list.sort()
print(list)

元组
作用:同列表类似
区别:元组不可变,不可被修改
# 使用元组
zoo = (‘wolf‘, ‘elephant‘, ‘penguin‘)
print ‘Number of animals in the zoo is‘, len(zoo)
new_zoo = (‘monkey‘, ‘dolphin‘, zoo)
print ‘Number of animals in the new zoo is‘, len(new_zoo)
print ‘All animals in new zoo are‘, new_zoo
print ‘Animals brought from old zoo are‘, new_zoo[2]
print ‘Last animal brought from old zoo is‘, new_zoo[2][2]

字典
作用:键和值联系。键是唯一的。没有顺序。
标记形式:d = {key1 : value1, key2 : value2 }
# 使用字典
ab = { ‘Swaroop‘ : ‘[email protected]‘,
‘Larry‘ : ‘[email protected]‘,
‘Matsumoto‘ : ‘[email protected]‘,
‘Spammer‘ : ‘[email protected]
}
print "Swaroop‘s address is %s" % ab[‘Swaroop‘]
66
# Adding a key/value pair
ab[‘Guido‘] = ‘[email protected]
# Deleting a key/value pair
del ab[‘Spammer‘]
len(ab)
for name, address in ab.items():
print (name, address)

序列:
包括:列表、元组、字符串
特点:索引操作符、切片操作符
使用:
# 使用序列
shoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]
# Indexing or ‘Subscription‘ operation
print ‘Item 0 is‘, shoplist[0]
print ‘Item 1 is‘, shoplist[1]
print ‘Item 2 is‘, shoplist[2]
print ‘Item 3 is‘, shoplist[3]
print ‘Item -1 is‘, shoplist[-1]
print ‘Item -2 is‘, shoplist[-2]
# Slicing on a list
print ‘Item 1 to 3 is‘, shoplist[1:3]
print ‘Item 2 to end is‘, shoplist[2:]
print ‘Item 1 to -1 is‘, shoplist[1:-1]
print ‘Item start to end is‘, shoplist[:]
# Slicing on a string
name = ‘swaroop‘
print ‘characters 1 to 3 is‘, name[1:3]
print ‘characters 2 to end is‘, name[2:]
print ‘characters 1 to -1 is‘, name[1:-1]
print ‘characters start to end is‘, name[:]

字符串的使用:
# 字符串使用
name = ‘Swaroop‘ # This is a string object
if name.startswith(‘Swa‘):
print ‘Yes, the string starts with "Swa"‘
if ‘a‘ in name:
print ‘Yes, it contains the string "a"‘
if name.find(‘war‘) != -1:
print ‘Yes, it contains the string "war"‘
delimiter = ‘_*_‘
mylist = [‘Brazil‘, ‘Russia‘, ‘India‘, ‘China‘]
print delimiter.join(mylist)

















































































以上是关于python基础知识:数据结构的学习的主要内容,如果未能解决你的问题,请参考以下文章

流畅python学习笔记:第十一章:抽象基类

Python3基础 issubclass 判断基类

Python3基础 issubclass 判断基类

python3 语法学习 类和继承

python基础学习日志day6-类的继承

机器学习强基计划8-1:图解主成分分析PCA算法(附Python实现)