学习内容:Data Structures
list、tuple、dictionary、set
Python内嵌的数据结构有四类:列表、元组、字典、集合。
List(列表)
列表是将一系列的项目放在同个数据中去。
好比我们要购物罗列的购物清单,上面写着很多需购置的物品名称。
列表数内的值是可变的,用commas“,”分隔开,外面用square brackets "[ ]"。
shoplist=['banana','apple','lemon','pea']
#using 'print' mathod is neatly
print(shoplist)
print('I have',len(shoplist),'items to buy.')
shoplist.append('orange')
print('Now the items number is:',len(shoplist))
# hence use the 'for',like print directly.
for i in shoplist:
print(i)
shoplist.sort()
print(shoplist)
#assume we have bought 'lemon',so remuve it
oldlist=shoplist[2]
del shoplist[2]
print('And after I bought the',oldlist,'\nnow my shoplist is:',shoplist)
Output
['banana', 'apple', 'lemon', 'pea']
I have 4 items to buy.
Now the items number is: 5
banana
apple
lemon
pea
orange
['apple', 'banana', 'lemon', 'orange', 'pea']
And after I bought the lemon
now my shoplist is: ['apple', 'banana', 'orange', 'pea']
如果想进一步了解list的其他函数,查看help(list)
Tuple(元组)
元组里面可以放不同类型的数据,包括其他元组。用逗号隔开,外面可以不用符号或用parentheses“()”,但是如果只有一个item的,最好用(item,) 这样表示,让Python知道这是个元组。
元组内的值可以直接用print函数,也可以通过索引来定位调取。
元组跟字符串一样,是不可变的。
举例说明,有个动物园有3种动物,现在搬至新动物园,原先动物不变,另外增加了三种动物。
zoo='tiger','lion','elephant'
print(zoo)
print('There are',len(zoo),'animals in zoo.')
#now the city has a new zoo
newzoo='pigeon','owl','sparrow',zoo
print('The new zoo has',len(newzoo),'cages')
print('Those animals from old zoo are:',newzoo[3])
print('The first animal from old zoo is:',newzoo[3][0])
# count the new zoo animal
print('Now new zoo has',len(newzoo)-1+len(zoo),'animals,/nand those animal are :',newzoo)
Output:
('tiger', 'lion', 'elephant')
There are 3 animals in zoo.
The new zoo has 4 cages
Those animals from old zoo are: ('tiger', 'lion', 'elephant')
The first animal from old zoo is: tiger
Now new zoo has 6 animals,/nand those animal are : ('pigeon', 'owl', 'sparrow', ('tiger', 'lion', 'elephant'))
Dictionary(字典)
字典就好像一本通讯录,我们可以通过姓名(keys)查找到该人电话号码等相关信息(values),两者相关联的,我们可称其为“key-value pairs(键值对)”,因为键和值都是成对成对出现,中间用colon“:”分开,并且“键”必须是唯一的,且只能用不可变的对象如string,键值对之间用逗号隔开。
类似:d = {key1 : value1, key2 : value2 }
# 'ab' is short for 'a'ddress'b'ook
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
print("Swaroop's address is", ab['Swaroop'])
# Deleting a key-value pair
del ab['Spammer']
print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
for name, address in ab.items():
print('Contact {} at {}'.format(name, address))
# Adding a key-value pair
ab['Guido'] = 'guido@python.org'
if 'Guido' in ab:
print("\nGuido's address is", ab['Guido'])
Output:
Swaroop's address is swaroop@swaroopch.com
There are 3 contacts in the address-book
Contact Swaroop at swaroop@swaroopch.com
Contact Larry at larry@wall.org
Contact Matsumoto at matz@ruby-lang.orgGuido's address is guido@python.org
Sequence
列表、元组、字符串都是数列的一种,他们最大的特点是成员关系的测试(可用in 或 not in表达式)和索引操作,由此我们可以直接进入所需的特定值。
上述三类还可以采用slicing operation(切片操作)来获取其中的一部分。
可以用负数做切片。负数用在从序列尾开始计算的位置。
shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
# 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])
print('Character 0 is', name[0])
# 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 #
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[:])
#Slicing with a third argument(when the step is 2, we get the items with position 0, 2,... When the step size #is 3, we get the items with position 0, 3, etc.)
print('slice with a third argument:',shoplist[::1])
print('slice with a third argument:',shoplist[::2])
print('slice with a third argument:',shoplist[::3])
print('slice with a third argument:',shoplist[::-1])
Outport:
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Character 0 is s
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
slice with a third argument: ['apple', 'mango', 'carrot', 'banana']
slice with a third argument: ['apple', 'carrot']
slice with a third argument: ['apple', 'banana']
slice with a third argument: ['banana', 'carrot', 'mango', 'apple']
set(集合)
当在聚集中一个对象的存在比其顺序或者出现的次数重要时使用集合。
使用集合,可以检查是否是成员,是否是另一个集合的子集,得到两个集合的交集等等。
也可用print函数和for loop来读取里面项目,但不能被索引和切片。
>>> bri = set(['brazil', 'russia', 'india'])
# the same as
# bri={'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'}
引用
当我们创建一个对象并指定它到一个变量,这个变量仅仅是指向这个对象,而不能代表这个对象本身,
它指向的是这个对象在计算机内存中的位置。
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist is just another name pointing to the same object!
mylist = shoplist
# I purchased the first item, so I remove it from the list( the same consequence of"del mylist")
del shoplist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
# Notice that both shoplist and mylist both print
# the same list without the 'apple' confirming that
# they point to the same object
print('Copy by making a full slice')
# Make a copy by doing a full slice
mylist = shoplist[:]
# Remove first item,the same consequence of"del shoplist"
del mylist[0]
print('shoplist is', shoplist)
print('mylist is', mylist)
# Notice that now the two lists are different
因此如果要完全创建一个全新的对象,可以用切片操作,比如 mylist = shoplist[:]
更多字符串用法
# This is a string object
name = 'Swaroop'
if name.startswith('Swa'):
print('Yes, the string starts with "Swa"')
if 'a' in name:
print('Yes, it contains the string "a"')
#find returns -1 if it is unsuccessful in finding the substring.
if name.find('war') != -1:
print('Yes, it contains the string "war"')
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
Outport:
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_RussiaIndia_China
学习Python第五天,花费的工夫不少,但是乐在其中。继续fighting!!!
网友评论