海牛部落 python 系列教程(三十七):python 基础 2

教程 青牛 ⋅ 于 2017-09-29 13:06:00 ⋅ 最后回复由 hxc 2023-12-21 16:26:43 ⋅ 13446 阅读

1.数据结构

Python中有三种内建的数据结构——列表、元组和字典
(30).列表
list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列 的项目。并且里面的值是能够被改变的
列表中的项目应该包括在方括号中,这样Python就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。
[1,2,3,4] 逗号分割
由于你可以增加或删除项目,我们说列表是 可变的 数据类型,即这种类型是可以被改变的。

代码示例
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,

print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist

print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist

print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist

print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符sort方法来对列表排序。需要理解的是,这个方法影响列表本身,而不是返回一个修改后的列表del语句为我们从列表中删除它。我们指明我们想要删除列表中的第一个元素,因此使用del shoplist[0]可以通过help(list)获得关于list完整的信息

file
(31).元组
元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。
代码示例
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]

元组是不能改变的
zoo.add('tiger')

file
元组结合打印语句
age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name

%s表示字符串或%d表示整数。元组必须按照相同的顺序来对应

file
(32).字典与集合
字典类似于java的map
只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以把不可变或可变的对象作为字典的值。基本说来就是,你应该只使用简单的对象作为键。键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。
字典是dict类的实例/对象。

代码示例
ab = { 'Swaroop' : 'swaroopch@byteofpython.info','Larry' : 'larry@wall.org','Matsumoto' : 'matz@ruby-lang.org','Spammer' : 'spammer@hotmail.com'}

print "Swaroop's address is %s" % ab['Swaroop']

Adding a key/value pair

ab['Guido'] = 'guido@python.org'

Deleting a key/value pair

del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)

循环

for name, address in ab.items():
print 'Contact %s at %s' % (name, address)

判断是否存在

if 'Guido' in ab: # OR ab.has_key('Guido')
print "\nGuido's address is %s" % ab['Guido']

del语句来删除键/值对。我们只需要指明字典和用索引操作符指明要删除的键,然后把它们传递给del语句
使用字典的items方法,来使用字典中的每个键/值对。这会返回一个元组的列表,其中每个元组都包含一对项目——键与对应的值,然后分别赋给for..in循环中的变量name和address
使用in操作符来检验一个键/值对是否存在,或者使用dict类的has_key方法

file
集合
set
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
要创建一个set,需要提供一个list作为输入集合:
s = set([1, 2, 3])
注意,传入的参数[1, 2, 3]是一个list,而显示的{1, 2, 3}只是告诉你这个set内部有1,2,3这3个元素,显示的顺序也不表示set是有序的。。
重复元素在set中自动被过滤:
s = set([1, 1, 2, 2, 3, 3])
通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果:
s.add(4)
{1, 2, 3, 4}
s.add(4)
通过remove(key)方法可以删除元素:
s.remove(4)
set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作:
s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
s1 & s2
{2, 3}
s1 | s2
{1, 2, 3, 4}
set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。试试把list放入set,看看是否会报错。

file
(33).列表、元组和字符串都可以看成一序列数据,都可以通过索引操作符让我们可以从序列中抓取一个特定项目或取其中一部分数据,也就是序列数据的切片
代码示例
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[:]

索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的
切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割,数是可选的,而冒号是必须的。
切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。

file
(34).引用
当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 引用 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。
代码示例
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist

print 'Copy by making a full slice'
mylist = shoplist[:]
del mylist[0] # remove first item
print 'shoplist is', shoplist
print 'mylist is', mylist

file
(35).对象的深拷贝与浅拷贝
代码示例
import copy
a = [1, 2, 3, 4, ['a', 'b']] #原始对象

b = a #赋值,传对象的引用
c = copy.copy(a) #对象拷贝,浅拷贝
d = copy.deepcopy(a) #对象拷贝,深拷贝

a.append(5) #修改对象a
a[4].append('c') #修改对象a中的['a', 'b']数组对象

print 'a = ', a
print 'b = ', b
print 'c = ', c
print 'd = ', d

file
(36).其它常用字符串的操作
代码示例
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)

file

2.对象

(37).self等于java的this
当你调用这个对象的方法
MyObject.method()的时候,这会由Python自动转为MyClass.method(MyObject),所以如果你有一个不需要参数的方法,你还是得给这个方法定义一个self参数。

创建一个类
代码示例
class Person:
pass # An empty block

p = Person()

在方法的对象
代码示例
class Person:
def sayHi(self):
print 'Hello, how are you?'

p = Person()
p.sayHi()

file
(38).init方法
init方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的 初始化 。注意,这个名称的开始和结尾都是双下划线。
类似于java的构造函数

代码示例
class Person:
def init(self, name):

回复帖子,然后刷新页面即可查看隐藏内容

版权声明:原创作品,允许转载,转载时务必以超链接的形式表明出处和作者信息。否则将追究法律责任。来自海汼部落-青牛,http://hainiubl.com/topics/190
回复数量: 49
暂无评论~~
  • 请注意单词拼写,以及中英文排版,参考此页
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`, 更多语法请见这里 Markdown 语法
  • 支持表情,可用Emoji的自动补全, 在输入的时候只需要 ":" 就可以自动提示了 :metal: :point_right: 表情列表 :star: :sparkles:
  • 上传图片, 支持拖拽和剪切板黏贴上传, 格式限制 - jpg, png, gif,教程
  • 发布框支持本地存储功能,会在内容变更时保存,「提交」按钮点击时清空
Ctrl+Enter