\t制表符
>>> print(‘python’) python >>> print(“python”) python >>> print(‘\tpython’) python \n换行符
>>> print(“Languages:\nPython\nC\nJavaScript”) Languages: Python C JavaScript >>> print(‘number:\n1\n2\n3’) number: 1 2 3 同时换行、制表,添加空白
>>> print(‘\n\t1\n\t2\n\t3’) 1 2 3 .rstrip()删除末尾多余空白,暂时性,永久,赋值到变量中
>>> favorite_language = ‘python ‘ >>> favorite_language ‘python ‘ >>> favorite_language.rstrip() ‘python’ >>> favorite_language = favorite_language.rstrip() >>> favorite_language File “<stdin>”, line 1 favorite_language ^ IndentationError: unexpected indent >>> favorite_language ‘python’ .rstrip()删除末尾空白 .lstrip()删除开头空白 .strip()删除两端空白
>>> number = ‘ 1 ‘ >>> number.strip() ‘1’ >>> number.lstrip() ‘1 ‘ **乘方 浮点数:带小数点的数字 str()转化为字符串
>>> message = ‘happy’ + age + ‘rd birthday!’ Traceback (most recent call last): File “<stdin>”, line 1, in <module> TypeError: can only concatenate str (not “int”) to str >>> message = “Happy ” + str(age) + “rd Birthday!” >>> print(message) Happy 23rd Birthday! 空格,空格,没有空格就会显示错误
>>> print(1+10) File “<stdin>”, line 1 print(1+10) ^ SyntaxError: invalid character in identifier >>> print(1 * 11) 11 在Python中,注释用井号( #)标识。井号后面的内容都会被Python解释器忽略,转行要继续添加#号,print语句中,没有被定义的一定要加引号,单引号双引号都可以
>>> #生日问候 … print(happy) Traceback (most recent call last): File “<stdin>”, line 2, in <module> NameError: name ‘happy’ is not defined >>> # 生日问候 … print(‘happy’) Tim Peters撰写的“Python之禅” 列表 索引从 0 而不是 1 开始
>>> bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’] >>> print(bicycles[0]) trek >>> print(bicycles[2].upper()) REDLINE Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为-1,可让Python返 回最后一个列表元素。 [-1]返回最后一个列表元素。
>>> bicycles = [‘trek’, ‘cannondale’, ‘redline’, ‘specialized’] >>> message = “My first bicycle was a ” + bicycles[-1].upper() + ‘.’ >>> print(message) My first bicycle was a SPECIALIZED. 空格是单独作为一个字符,不要丢
>>> name = [‘mike’,’john’,’lisa’] >>> message = name[-1].title() + ‘is my sex partner.’ >>> print(message) Lisais my sex partner. >>> message = name[-1].title() + ‘ is my sex partner.’ >>> print(message) Lisa is my sex partner. 你创建的大多数列表都将是动态的,这意味着列表创建后,将随着程序的运行增删元素。例如,你创建一个游戏,要求玩家射杀从天而降的外星人;为此,可在开始时将一些外星人存储在列表中,然后每当有外星人被射杀时,都将其从列表中删除,而每次有新的外星人出现在屏幕上时,都将其添加到列表中。在整个游戏运行期间,外星人列表的长度将不断变化。(要理解这种算法的思路) 修改列表中第一个元素的值
>>> motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’] >>> print(motorcycles) [‘honda’, ‘yamaha’, ‘suzuki’] >>> motorcycles[0] = ‘ducati’ # 空格会显示错误 File “<stdin>”, line 1 motorcycles[0] = ‘ducati’ ^ IndentationError: unexpected indent >>> motorcycles[0] = ‘ducati’ #修改列表中第一个元素的值 >>> print(motorcycles) [‘ducati’, ‘yamaha’, ‘suzuki’] .append()列表末尾添加元素,only one
>>> motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’] >>> print(motorcycles) [‘honda’, ‘yamaha’, ‘suzuki’] >>> motorcycles.append(‘ducati’) >>> print(motorcycles) [‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’] >>> motorcycles.append(‘A’,’B’) Traceback (most recent call last): File “<stdin>”, line 1, in <module> TypeError: append() takes exactly one argument (2 given)
.insert(索引,值) 使用方法insert()可在列表的任何位置添加新元素 从列表中删除元素 你经常需要从列表中删除一个或多个元素。例如,玩家将空中的一个外星人射杀后,你很可能要将其从存活的外星人列表中删除;当用户在你创建的Web应用中注销其账户时,你需要将该用户从活跃用户列表中删除。你可以根据位置或值来删除列表中的元素。 使用del语句删除元素:使用del语句将值从列表中删除后,你就无法再访问
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’] print(motorcycles) del motorcycles[0] print(motorcycles) 使用方法pop()删除元素:方法pop()(弹出)可删除列表末尾的元素,并让你能够接着使用它
>>> motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’] >>> print(motorcycles) [‘honda’, ‘yamaha’, ‘suzuki’] >>> popped_motorcycle = motorcycles.pop() >>> print(motorcycles) [‘honda’, ‘yamaha’] >>> print(popped_motorcycle) suzuki .pop()删除列表末尾元素,并且可以接着使用该元素 可以使用pop()来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。 如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()。 不知道要从列表中删除的值所处的位置。如果你只知道要删除的元素的值,可使用方法remove()。 使用remove()从列表中删除元素时,也可接着使用它的值。
motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’] print(motorcycles) too_expensive = ‘ducati’ motorcycles.remove(too_expensive) print(motorcycles) print(“\nA ” + too_expensive.title() + ” is too expensive for me.”)
.remove()删除不知道列表中元素位置的值,并且可以继续使用该值。 方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要 使用循环来判断是否删除了所有这样的值。
>>> lisi = [‘A’,’B’,’C’] >>> list = [‘a’,’b’,’c’,’d’] >>> list[0] = ‘e’ >>> print(list) [‘e’, ‘b’, ‘c’, ‘d’] >>> print(list.title()) Traceback (most recent call last): File “<stdin>”, line 1, in <module> AttributeError: ‘list’ object has no attribute ‘title’ >>> list.append(f) Traceback (most recent call last): File “<stdin>”, line 1, in <module> NameError: name ‘f’ is not defined >>> list.append(‘f’) >>> print(list) [‘e’, ‘b’, ‘c’, ‘d’, ‘f’] >>> del list[-1] >>> print(list) [‘e’, ‘b’, ‘c’, ‘d’] >>> list.pop() ‘d’ >>> print(list) [‘e’, ‘b’, ‘c’] >>> list.pop(1) ‘b’ >>> print(list) [‘e’, ‘c’] >>> list = [‘a’,’b’,’c’,’d’,’e’,’f’] >>> list.remove(‘a’) >>> print(list) [‘b’, ‘c’, ‘d’, ‘e’, ‘f’] >>> list.insert(1,’z’) >>> print(list) [‘b’, ‘z’, ‘c’, ‘d’, ‘e’, ‘f’]
组织列表,排序 使用方法 sort()对列表进行永久性排序 字母顺序
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’] cars.sort() print(cars)
字母顺序相反
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’] cars.sort(reverse=True) print(cars)
1.现在提前假设都是小写,问题还没完
>>> cars = [‘a’,’c’,’b’] >>> cars = cars.sort() >>> print(cars) None >>> cars = [‘a’,’c’,’b’] >>> cars.sort() >>> print(cars) [‘a’, ‘b’, ‘c’] >>> cars.sort(reverse = true) Traceback (most recent call last): File “<stdin>”, line 1, in <module> NameError: name ‘true’ is not defined >>> cars.sort(reverse=true) Traceback (most recent call last): File “<stdin>”, line 1, in <module> NameError: name ‘true’ is not defined >>> cars.sort(reverse = True) >>> print(cars) [‘c’, ‘b’, ‘a’] >>> print(cars.title()) Traceback (most recent call last): File “<stdin>”, line 1, in <module> AttributeError: ‘list’ object has no attribute ‘title’ 使用函数 sorted()对列表进行临时排序
>>> cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’] >>> print(“Here is the original list:”) Here is the original list: >>> print(cars) [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’] >>> print(sorted(cars)) [‘audi’, ‘bmw’, ‘subaru’, ‘toyota’] >>> print(cars) [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’] 要反转列表元素的排列顺序,可使用方法reverse() .reverse()反转列表元素顺序
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’] print(cars) cars.reverse() print(cars) print(len(cars)) 4 方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此 只需对列表再次调用reverse()即可。 使用函数len()可快速获悉列表的长度,列表中有几个元素就显示几。 操作列表:
>>> magicians = [‘alice’, ‘david’, ‘carolina’] >>> for magician in magicians: … print(magician) File “<stdin>”, line 2 print(magician) ^ IndentationError: expected an indented block >>> magicians = [‘alice’, ‘david’, ‘carolina’] >>> for magician in magicians: … print(magician) … alice david carolina >>> magicians = [‘alice’, ‘david’, ‘carolina’] >>> for A in magicians: … print(A) … alice david carolina
缩进不对不行,for循环后面要加冒号,A or magician 是自己命名的,存储变量用,(这行代码让Python从列表magicians中取出一个名字,并将其存储在变量magician中)
for cat in cats: for dog in dogs: for item in list_of_items:
以上操作方式是便于你理解
>>> magicians = [‘alice’, ‘david’, ‘carolina’] >>> for magician in magicians: … print(magician.title() + “, that was a great trick!”) … Alice, that was a great trick! David, that was a great trick! Carolina, that was a great trick!
示例二:
>>> magicians = [‘alice’, ‘david’, ‘carolina’] >>> for magician in magicians: … print(magician.title() + “, that was a great trick!”) # 第一次循环 … print(“I can’t wait to see your next trick, ” + magician.title() + “.\n” ) … Alice, that was a great trick! I can’t wait to see your next trick, Alice. David, that was a great trick! I can’t wait to see your next trick, David. Carolina, that was a great trick! I can’t wait to see your next trick, Carolina. 在for循环后面,没有缩进的代码都只执行一次,而不会重复执行。
print(“Thank you, everyone. That was a great magic show!”)
创建数值列表: Python函数range()让你能够轻松地生成一系列的数字: range(1,5)函数range()让Python从你指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出不包含第二个值(这里为5)。
>>> for value in range(1,6): … print(value) … 1 2 3 4 5 使用 list()创建数字列表,要创建数字列表,可使用函数list()将range()的结果直接转换为列表。
>>> numbers = list(range(1,6)) >>> print(numbers) [1, 2, 3, 4, 5] >>> even_numbers = list(range(2,11,2)) >>> print(even_numbers) [2, 4, 6, 8, 10]
range(x,y,z)
x起始
y停止
z步长(可以不写) 数range()让你能够轻松地生成一系列的数字
range(2, 15, 2) >>> for value in range(1,6,2): … print(value) … 1 3 5 如何创建一个列表,其中包含前10个整数(即1~10)的平方呢?
>>> squares = [] >>> for value in range(1,11): … square = value**2 … squares.append(square) … >>> print(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
使代码简化
>>> squares = [] >>> for value in range(1,11): … squares.append(value**2) … >>> print(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
继续简化:
>>> squares = [value**2 for value in range(1,11)] >>> print(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 请注意,这里的for语句末尾没有冒号。 要使用这种语法,首先指定一个描述性的列表名,如squares;然后,指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值。在这个示例中,表达式为value**2,它计算平方值。接下来,编写一个for循环,用于给表达式提供值,再加上右方括号。 列表名+循环
数值计算
>>> digits = list(range(0,10)) >>> print(digits) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> min(digits) 0 >>> max(digits) 9 >>> sum(digits) 45
练习:
>>> numbers = list(range(1,21)) >>> print(numbers) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] >>> for value in range(1,21): … print(value) … 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
>>> numbers = list(range(1,1000001)) >>> min(numbers) 1 >>> max(numbers) 1000000 >>> numbers[0] 1 >>> numbers[-1] 1000000 >>> sum(numbers) 500000500000
>>> numbers = [value**3 for value in range(1,11)] >>> print(numbers) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]