列表是一种用于保存一系列有序项目的集合。项目的列表应该用方括号括起来,这样 Python 才能理解到你正在指定一张列表。一旦你创建了一张列表,你可以添加、移除或搜索列表中的项目。
shoplist = ['apple', 'mango', 'carrot', 'banana']print('I have', len(shoplist), 'items to purchase.')print('These items are:', end=' ')
for item in shoplist:print(item, end=' ')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)
#输出
#I have 4 items to purchase.
#These items are: apple mango carrot banana
#I also have to buy rice.
#My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
#I will sort my list now
#Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
#The first item I will buy is apple
#I bought the apple
#My shopping list is now ['banana', 'carrot', 'mango', 'rice']
zoo = ('python', 'elephant', 'penguin')
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)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',len(new_zoo)-1+len(new_zoo[2]))
#输出
#Number of animals in the zoo is 3
#Number of cages in the new zoo is 3
#All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
#Animals brought from old zoo are ('python', 'elephant', 'penguin')
#Last animal brought from old zoo is penguin
#Number of animals in the new zoo is 5
字典将键值(Keys)(即姓名)与值(Values)(即地
址等详细信息)联立到一起,在这里要注意到键值必须是唯一的。
ab = {'Swaroop': 'swaroop@swaroopch','Larry': 'larry@wall','Matsumoto': 'matz@ruby-lang','Spammer': 'spammer@hotmail'
}print("Swaroop's address is", ab['Swaroop'])
# 删除一对键值—值配对del ab['Spammer']print('nThere are {} contacts in the address-bookn'.format(len(ab)))for name, address in ab.items():print('Contact {} at {}'.format(name, address))# 添加一对键值—值配对
ab['Guido'] = 'guido@python'if 'Guido' in ab:print("nGuido's address is", ab['Guido'])
#输出
#Swaroop's address is swaroop@swaroopch
#There are 3 contacts in the address-book
#Contact Swaroop at swaroop@swaroopch
#Contact Matsumoto at matz@ruby-lang
#Contact Larry at larry@wall
#Guido's address is guido@python
列表、元组和字符串可以看作序列(Sequence)的某种表现形式。上面所提到的序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing)运算符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。
shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'# Indexing or 'Subscription' operation #
# 索引或“下标(Subscription)”操作符 #
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[:])# 从某一字符串中切片 #
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[:])
#输出
#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
>>> shoplist = ['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::1]
['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::2]
['apple', 'carrot']
>>> shoplist[::3]
['apple', 'banana']
>>> shoplist[::-1]
['banana', 'carrot', 'mango', 'apple']
集合(Set)是简单对象的无序集合(Collection)。当集合中的项目存在与否比起次序或其出现次数更加重要时,我们就会使用集合。
通过使用集合,可以测试某些对象的资格或情况,检查它们是否是其它集合的子集,找到两个集合的交集。
>> bri = set(['brazil', 'russia', 'india'])
>>> 'india' in bri
True
>>> 'usa' in bri
False
>>> bric = py()
>>> bric.add('china')
>>> bric.issuperset(bri)
True
>>> ve('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}
当你创建了一个对象并将其分配给某个变量时,变量只会查阅(Refer)某个对象,并且它也不会代表对象本身。也就是说,变量名只是指向你计算机内存中存储了相应对象的那一部分。这叫作将名称绑定(Binding)给那一个对象。
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist 只是指向同一对象的另一种名称
mylist = shoplist# 我购买了第一项项目,所以我将其从列表中删除
del shoplist[0]print('shoplist is', shoplist)
print('mylist is', mylist)
# 注意到 shoplist 和 mylist 二者都
# 打印出了其中都没有 apple 的同样的列表,以此我们确认
# 它们指向的是同一个对象print('Copy by making a full slice')
# 通过生成一份完整的切片制作一份列表的副本
mylist = shoplist[:]
# 删除第一个项目
del mylist[0]print('shoplist is', shoplist)
print('mylist is', mylist)
# 注意到现在两份列表已出现不同#输出
#Simple Assignment
#shoplist is ['mango', 'carrot', 'banana']
#mylist is ['mango', 'carrot', 'banana']
#Copy by making a full slice
#shoplist is ['mango', 'carrot', 'banana']
#mylist is ['carrot', 'banana']
两个list出现不同的主要原因是,前一个操作是句柄拷贝,指向的是同一个对象;后一个操作是对象拷贝,所以进行del操作时没有影响原始数据。
# 这是一个字符串对象
name = 'Swaroop'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))
#输出
#Yes, the string starts with "Swa"
#Yes, it contains the string "a"
#Yes, it contains the string "war"
#Brazil_*_Russia_*_India_*_China
类方法与普通函数只有一种特定的区别——前者必须有一个额外的名字,这个名字必须添加到参数列表的开头,但是你不用在你调用这个功能时为这个参数赋值,Python 会为它提供。这种特定的变量引用的是对象本身,按照惯例,它被赋予 self 这一名称。
(Python 中的 self 相当于 C++ 中的指针以及 Java 与 C# 中的 this 指针。)
最简单的类(Class)如下:
class Person:pass # 一个空的代码块p = Person()
print(p)
class Person:def say_hi(self):print('Hello, how are you?')p = Person()
p.say_hi()
# 前面两行同样可以写作
# Person().say_hi()#输出
#Hello, how are you?
say_hi 这一方法不需要参数,但是依旧在函数定义中拥有 self 变量。
init 方法会在类的对象被实例化(Instantiated)时立即运行。这一方法可以对任何你想进行操作的目标对象进行初始(Initialization)操作。这里你要注意在 init 前后加上的双下划线。
class Person:def __init__(self, name):self.name = namedef say_hi(self):print('Hello, my name is', self.name)p = Person('Swaroop')
p.say_hi()
# 前面两行同时也能写作
# Person('Swaroop').say_hi()#输出
#Hello, my name is Swaroop
class Robot:# 一个类变量,用来计数机器人的数量population = 0def __init__(self, name):self.name = nameprint("(Initializing {})".format(self.name))# 当有人被创建时,机器人# 将会增加人口数量Robot.population += 1def die(self):print("{} is being destroyed!".format(self.name))Robot.population -= 1if Robot.population == 0:print("{} was the last one.".format(self.name))else:print("There are still {:d} robots working.".format(Robot.population))def say_hi(self):print("Greetings, my masters call me{}.".format(self.name))@classmethod
def how_many(cls):print("We have {:d} robots.".format(cls.population))droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()
droid2 = Robot("C-3PO")
droid2.say_hi()
Robot.how_many()
print("nRobots can do some work here.n")
print("Robots have finished their work. So let's destroy them.")
droid1.die()
droid2.die()
Robot.how_many()#输出
#(Initializing R2-D2)
#Greetings, my masters call me R2-D2.
#We have 1 robots.
#(Initializing C-3PO)
#Greetings, my masters call me C-3PO.
#We have 2 robots.#Robots can do some work here.#Robots have finished their work. So let's destroy them.
#R2-D2 is being destroyed!
#There are still 1 robots working.
#C-3PO is being destroyed!
#C-3PO was the last one.
#We have 0 robots.
面向对象编程的一大优点是对代码的重用,重用的一种实现方法就是通过继承机制。
class SchoolMember:'''代表任何学校里的成员。'''def __init__(self, name, age):self.name = nameself.age = ageprint('(Initialized SchoolMember: {})'.format(self.name))def tell(self):'''告诉我有关我的细节。'''print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")class Teacher(SchoolMember):'''代表一位老师。'''def __init__(self, name, age, salary):SchoolMember.__init__(self, name, age)self.salary = salaryprint('(Initialized Teacher: {})'.format(self.name))def tell(self):ll(self)print('Salary: "{:d}"'.format(self.salary))class Student(SchoolMember):'''代表一位学生。'''def __init__(self, name, age, marks):SchoolMember.__init__(self, name, age)self.marks = marksprint('(Initialized Student: {})'.format(self.name))def tell(self):ll(self)print('Marks: "{:d}"'.format(self.marks))t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75)# 打印一行空白行
print()members = [t, s]
for member in members:# 对全体师生工作ll()
#输出
#(Initialized SchoolMember: Mrs. Shrividya)
#(Initialized Teacher: Mrs. Shrividya)
#(Initialized SchoolMember: Swaroop)
#(Initialized Student: Swaroop)#Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
#Name:"Swaroop" Age:"25" Marks: "75"
例子中teacher和student即schoolmate的子类,由于python中默认虚方法。所以调用子类而非父类的方法。
具体有关多态部分的内容可参考:SV中的OOP四、类的三要素3.多态
def reverse(text):return text[::-1]def is_palindrome(text):return text == reverse(text)something = input("Enter text: ")
if is_palindrome(something):print("Yes, it is a palindrome")
else:print("No, it is not a palindrome")#输出
#Enter text: sir
#No, it is not a palindrome
#Enter text: madam
#Yes, it is a palindrome
可以通过创建一个属于 file 类的对象并适当使用它的 read 、 readline 、 write 方法来打开或使用文件,并对它们进行读取或写入。读取或写入文件的能力取决于你指定以何种方式打开文件。最后,当你完成了文件,你可以调用 close 方法来告诉 Python 已经完成了对该文件的使用。
poem = '''
Programming is fun
When the work is done
if you wanna make your work also fun:use Python!
'''# 打开文件以编辑('w'riting)
f = open(', 'w')
# 向文件中编写文本
f.write(poem)
# 关闭文件
f.close()# 如果没有特别指定,
# 将假定启用默认的阅读('r'ead)模式
f = open(')
while True:line = f.readline()# 零长度指示 EOFif len(line) == 0:break# 每行(`line`)的末尾# 都已经有了换行符#因为它是从一个文件中进行读取的print(line, end='')
# 关闭文件
f.close()#输出
#Programming is fun
#When the work is done
#if you wanna make your work also fun:
# use Python!
Python 提供了一个叫作 Pickle 的标准模块,通过它你可以将任何纯 Python 对象存储到一个文件中,并在稍后将其取回。这叫作持久地(Persistently)存储对象。
import pickle# The name of the file where we will store the object
shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = ['apple', 'mango', 'carrot']# Write to the file
f = open(shoplistfile, 'wb')
# Dump the object to a file
pickle.dump(shoplist, f)
f.close()# Destroy the shoplist variable
del shoplist# Read back from the storage
f = open(shoplistfile, 'rb')
# Load the object from the file
storedlist = pickle.load(f)
print(storedlist)#输出
#['apple', 'mango', 'carrot']
我们阅读或写入某一文件时,需要将我们的 Unicode 字符串转换至“UTF-8”格式。
import iof = io.open(", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()text = io.open(", encoding="utf-8").read()
print(text)
如果把 print 误拼成 Print ,Python 会抛出(Raise)一个语法错误同时 Python 还会打印出检测到的错误发生的位置。这就是一个错误错误处理器(Error Handler) 为这个错误所做的事情。。
>>> Print("Hello World")
Traceback (most recent call last):File "<stdin>", line 1, in <module>
NameError: name 'Print' is not defined
>>> print("Hello World")
Hello World
可以通过使用 try…except 来处理异常状况。一般来说我们会把通常的语句放在 try 代码块中,将我们的错误处理器代码放置在 except 代码块中。
try:text = input('Enter something --> ')
except EOFError:print('Why did you do an EOF on me?')
except KeyboardInterrupt:print('You cancelled the operation.')
else:print('You entered {}'.format(text))#输出
#Press ctrl + d
#Enter something --> Why did you do an EOF on me?#Press ctrl + c
#Enter something --> You cancelled the operation.#Enter something --> No exceptions
#You entered No exceptions
可以通过 raise 语句来引发一次异常,具体方法是提供错误名或异常名以及要抛出异常的对象。
你能够引发的错误或异常必须是直接或间接从属于 Exception (异常) 类的派生类。
class ShortInputException(Exception):'''一个由用户定义的异常类'''def __init__(self, length, atleast):Exception.__init__(self)self.length = lengthself.atleast = atleasttry:text = input('Enter something --> ')if len(text) < 3:raise ShortInputException(len(text), 3)# 其他工作能在此处继续正常运行
except EOFError:print('Why did you do an EOF on me?')
except ShortInputException as ex:print(('ShortInputException: The input was ' +'{0} long, expected at least {1}').format(ex.length, ex.atleast))
else:print('No exception was raised.')#输出
#Enter something --> a
#ShortInputException: The input was 1 long, expected at least 3
#Enter something --> abc
#No exception was raised.
假设你正在你的读取中读取一份文件。可以通过 finally 块来确保文件对象被正确关闭。
import sys
import timef = None
try:f = open(")# 我们常用的文件阅读风格while True:line = f.readline()if len(line) == 0:breakprint(line, end='')sys.stdout.flush()print("Press ctrl+c now")# 为了确保它能运行一段时间time.sleep(2)
except IOError:print("Could not find ")
except KeyboardInterrupt:print("!! You cancelled the reading from the file.")
finally:if f:f.close()print("(Cleaning up: Closed the file)")#输出
#Programming is fun
#Press ctrl+c now
#!! You cancelled the reading from the file.
#(Cleaning up: Closed the file)
在 try 块中获取资源,然后在 finally 块中释放资源是一种常见的模式。因此,还有一个with 语句使得这一过程可以以一种干净的姿态得以完成。
with open(") as f:for line in f:print(line, end='')
sys 模块包括了一些针对特定系统的功能。
比如我们需要检查正在使用的 Python 软件的版本, sys 模块会给我们相关的信息。
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=5, micro=1, releaselevel='final', serial=0)
>>> sys.version_info.major == 3
True
sys 模块包含一个 version_info 元组,它提供给我们版本信息。第一个条目是主版本信息。我们可以调出这些信息并使用它。
如果你想将一些调试信息或一些重要的信息储存在某个地方,以便你可以检查你的程序是否如你所期望那般运行,可以通过 logging 模块来实现。
import os
import platform
import loggingif platform.platform().startswith('Windows'):logging_file = os.path.v('HOMEDRIVE'),os.getenv('HOMEPATH'),'test.log')
else:logging_file = os.path.v('HOME'),'test.log')
print("Logging to", logging_file)logging.basicConfig(level=logging.DEBUG,format='%(asctime)s : %(levelname)s : %(message)s',filename=logging_file,filemode='w',
)logging.debug("Start of the program")
logging.info("Doing something")
logging.warning("Dying now")#输出
#Logging to /Users/swa/test.log#2014-03-29 09:27:36,660 : DEBUG : Start of the program
#2014-03-29 09:27:36,660 : INFO : Doing something
#2014-03-29 09:27:36,660 : WARNING : Dying now
使用一个元组从一个函数中返回两个不同的值。
>>> def get_error_details():
... return (2, 'details')
...
>>> errnum, errstr = get_error_details()
>>> errnum
2
>>> errstr
'details'
要注意到 a, b = 的用法会将表达式的结果解释为具有两个值的一个元
组。
这也意味着在 Python 中交换两个变量的最快方法是:
>>> a = 5; b = 8
>>> a, b
(5, 8)
>>> a, b = b, a
>>> a, b
(8, 5)
每一个语句块都由其自身的缩进级别与其它部分相区分。但是如果你的语句块只包括单独的一句语句,那么你可以在同一行指定它,例如条件语句与循环语句。
>>> flag = True
>>> if flag: print('Yes')
...
Yes
lambda 语句可以创建一个新的函数对象。从本质上说, lambda 需要一个参数,后跟一个表达式作为函数体,这一表达式执行的值将作为这个新函数的返回值。
points = [{'x': 2, 'y': 3},{'x': 4, 'y': 1}]
points.sort(key=lambda i: i['y'])
print(points)#输出
#[{'y': 1, 'x': 4}, {'y': 3, 'x': 2}]
一个 list 的 sort 方法可以获得一个 key 参数,用以决定列表的排序方式(通常我们只知道升序与降序)。在我们的案例中,我们希望进行一次自定义排序,为此我们需要编写一个函数,但是又不是为函数编写一个独立的 def 块,只在这一个地方使用,因此我们使用 Lambda 表达式来创建一个新函数。
列表推导用于从一份现有的列表中得到一份新列表。
比如现在你已经有了一份数字列表,你想得到一个相应的列表,其中的数字在大于 2 的情况下将乘以2:
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print(listtwo)#输出
#[6, 8]
使用列表推导的优点在于,当我们使用循环来处理列表中的每个元素并将其存储到新的列表中时时,它能减少样板代码的数量。
有一种特殊方法,即分别使用 * 或 ** 作为元组或字典的前缀,来使它们作为一个参数为函数所接收。当函数需要一个可变数量的实参时,这将颇为有用。
>>> def powersum(power, *args):
... '''Return the sum of each argument raised to the specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25#3x3+4x4
>>> powersum(2, 10)
100#10x10
因为我们在 args 变量前添加了一个 * 前缀,函数的所有其它的额外参数都将传递到args 中,并作为一个元组予以储存。如果采用的是 ** 前缀,则额外的参数将被视为字典的键值—值配对。
assert 语句用以断言某事是真的。如果其不是真的,就抛出一个错误。当语句断言失败时,将会抛出 AssertionError 。
>>> mylist = ['item']
>>> assert len(mylist) >= 1
>>> mylist.pop()
'item'
>>> assert len(mylist) >= 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
装饰器(Decorators)是应用包装函数的快捷方式。这有助于将某一功能与一些代码一遍又一遍地“包装”。举个例子,我为自己创建了一个 retry 装饰器,这样我可以将其运用到任何函数之中,如果在一次运行中抛出了任何错误,它就会尝试重新运行,直到最大次数 5 次,并且每次运行期间都会有一定的延迟。这对于你在对一台远程计算机进行网络调用的情况十分有用:
from time import sleep
from functools import wraps
import logging
logging.basicConfig()
log = Logger("retry")def retry(f):@wraps(f)def wrapped_f(*args, **kwargs):MAX_ATTEMPTS = 5for attempt in range(1, MAX_ATTEMPTS + 1):try:return f(*args, **kwargs)ption("Attempt %s/%s failed : %s",attempt,MAX_ATTEMPTS,(args, kwargs))sleep(10 * itical("All %s attempts failed : %s",MAX_ATTEMPTS,(args, kwargs))return wrapped_fcounter = 0@retry
def save_to_database(arg):print("Write to a database or make a network call or etc.")print("This will be automatically retried if exception is thrown.")global countercounter += 1# 这将在第一次调用时抛出异常# 在第二次运行时将正常工作(也就是重试)if counter < 2:raise ValueError(arg)if __name__ == '__main__':save_to_database("Some bad value")#输出
#Write to a database or make a network call or etc.
#This will be automatically retried if exception is thrown.
#ERROR:retry:Attempt 1/5 failed : (('Some bad value',), {})
#Traceback (most recent call last):
# File "more_decorator.py", line 14, in wrapped_f
# return f(*args, **kwargs)
# File "more_decorator.py", line 39, in save_to_database
# raise ValueError(arg)
#ValueError: Some bad value
#Write to a database or make a network call or etc.
#This will be automatically retried if exception is thrown.
本文发布于:2024-02-02 04:03:36,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170681796541235.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |