python data structure
List(列表)、Tuple(元组)、Dictionary(字典)、Set(集合)和Sequences(序列)
list
无固定长度,可变。
- list的部分截取:
- list元素的搜索:
animals = [“aardvark”, “badger”, “duck”, “emu”, “fennec fox”]
duck_index = animals.index(“duck”) - list元素的插入:
animals.insert(1, “dog”) #insert “dog” at 1 and move others by one
print animals - list元素的排序:
list.sort() - list删除:
常用 的三个版本:
list.pop(i) #删除的元素是第i+1个,返回元素
list.remove(i) #删除的元素是第i个,返回下标
del list[i] #不返回任何元素
Dictionary
无固定长度,可变,存储键值对。
residents = {‘Puffin’ : 104, ‘Sloth’ : 105, ‘Burmese Python’ : 106}
print residents[‘Puffin’] # Prints Puffin’s room number
- 加入新的元素:
menu = {} # Empty dictionary
menu[‘Chicken Alfredo’] = 14.50 # Adding new key-value pair - 删除元素:
del menu[‘Chicken Alfredo’] - 存储不同类型的键值对:
Tuple
不可变,功能不如List强大。
来自A Byte Of Python的例子:
Set
它不关注元素的顺序,不关心元素出现的次数,仅仅考虑是否出现,以及集合的交等操作。
来自A Byte of Python的例子:
Sequences
序列,和元组类似。注意下标的灵活应用
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(‘Item -2 is’, shoplist[-2]) #carrot
shoplist[::2] #[‘apple’, ‘carrot’] shoplist[0] , shoplist[2] 2为步长
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
mylist = shoplist #引用
mylist = shoplist[:] #copy
其他语法笔记
dir 函数来列出模块定义的标识符。
标识符有函数、类和变量。当你为 dir() 提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。
查看方法或者类的属性:
数字转字符串:
print “The value of pi is around ” + str(3.14)
python读写文件,可自动关闭。
with open(“text.txt”, “w”) as textfile:
textfile.write(“Success!”)
help(str) #查看string帮助
mylist = [‘Brazil’, ‘Russia’, ‘India’, ‘China’]
print(delimiter.join(mylist)) #Brazil_*_Russia_*_India_*_China
类编程:
__init__():
__init__ 方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的初始化。注意,这个名称的开始和结尾都是双下划线。init 方法相当于C++,Java,C# 中的构造函数
关于range()有三个版本:
1.range(stop)
2.range(start, stop)
3.range(start, stop, step)
math_var = 3 ** 3
27 # 这是一个指数运算
What is the data type for the following “false”?
False才是布尔值,这是string
获取第5个字符:
fifth_letter = “MONTY”[4]
格式化输出:
print “There are %d items in the suitcase.” % (list_length)