python data structure
List(列表)、Tuple(元组)、Dictionary(字典)、Set(集合)和Sequences(序列)
list
无固定长度,可变。
- list的部分截取:
-
animals = "catdogfrog" cat = animals[:3] # The first three characters of animals dog = animals[3:6] # The fourth through sixth characters frog = animals[6:] # From the seventh character to the end
- 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’]
- 存储不同类型的键值对:
-
my_dict = { "fish": ["c", "a", "r", "p"], "cash": -4483, "luck": "good" } print my_dict["fish"][0]
Tuple
不可变,功能不如List强大。
来自A Byte Of Python的例子:zoo = ('python', 'elephant', 'penguin') # remember the parentheses are optional print('Number of animals in the zoo is', len(zoo)) new_zoo = ('monkey', 'camel', zoo) print('Number of cages in the new zoo is', len(new_zoo)) print('All animals in new zoo are', new_zoo)
Set
它不关注元素的顺序,不关心元素出现的次数,仅仅考虑是否出现,以及集合的交等操作。
来自A Byte of Python的例子:>>> bri = set(['brazil', 'russia', 'india']) >>> 'india' in bri True >>> 'usa' in bri False >>> bric = bri.copy() >>> bric.add('china') >>> bric.issuperset(bri) True >>> bri.remove('russia') >>> bri & bric # OR bri.intersection(bric) {'brazil', 'india'}
Sequences
序列,和元组类似。注意下标的灵活应用
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(‘Item -2 is’, shoplist[-2]) #carrotshoplist[::2] #[‘apple’, ‘carrot’] shoplist[0] , shoplist[2] 2为步长
shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
mylist = shoplist #引用
mylist = shoplist[:] #copy其他语法笔记
dir 函数来列出模块定义的标识符。
标识符有函数、类和变量。当你为 dir() 提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。>>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> a=12 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a']
查看方法或者类的属性:
>>> dir(print) ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
数字转字符串:
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)