python 基础2

2018-09-14  本文已影响0人  彗色

操作列表

遍历列表(可迭代的--Iterable)

for 循环

  1. 如何判断一个对象是可迭代对象呢?方法是通过collections模块Iterable类型判断:
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
  1. Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身
>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
...
0 A
1 B
2 C
>>> magicians = ['alice', 'david', 'carolina']

>>> for magician in magicians:
    print(magician)

alice
david
carolina

函数range()

如果要打印数字0~5,可用range(0,6)

>>> for i in range(0,5):
    print(i)

0
1
2
3 
4

'''
扩展模式,else语句在for循环正常执行之后才执行并结束
for <循环变量>  in  <遍历结构>:
    <语句块1>
else:
   <语句块2>
 '''
for s in "PY":
    print("循环执行中: " + s)
else:
    s = "循环正常结束"
print(s)
 
>>> 
循环执行中: P
循环执行中: Y
循环正常结束

>>> number = list(range(1,6))

>>> print(number)
[1, 2, 3, 4, 5]
>>> number_2 = list(range(2,11,2))

>>> print(number_2)
[2, 4, 6, 8, 10]

对数字列表执行简单的统计计算

>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45

切片(处理列表的部分元素)

>>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
# 未省略0
>>> print(players[0:3])
['charles', 'martina', 'michael']
# 省略0
>>> print(players[ :3])
['charles', 'martina', 'michael']
>>> players[-1]
'eli'
>>> players[-2:]
['florence', 'eli']
>>> players[-2:-1]
['florence']
>>> players[-4]
'martina'
  • tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple
  • 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串

遍历切片

>>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
>>> for player in players[:3]:
     print(player.title())

Charles
Martina
Michael

复制列表

元组(tuple)——(‘name’,“life”,2,3)

列表是可以修改的,而不可变的列表被称为元组

定义元组

>>> dimensions = (200, 50)
>>> for dimension in dimensions:
    print(dimension)

200
50
>>> dimensions = (400, 100) # 重新定义一个新的元组
>>> for dimension in dimensions:
    print(dimension)

400
100

if 语句

条件测试

每条if 语句的核心都是一个值为TrueFalse 的表达式,这种表达式被称为条件测试

检查相等时无需考虑大小写

条件语句中可包含各种数学比较,如小于、小于等于、大于、大于

检查多个条件

>>> age_0 = 22
>>> age_1 = 18

>>> (age_0>= 21) and (age_1>=21)
False

>>> (age_0>= 21) and (age_1>=10)
True
>>> age_0 = 22
>>> age_1 = 18

>>> (age_0 >= 21) or (age_1 >= 21)  
True                                # 仅一个条件满足

>>> age_0 = 18
>>> (age_0 >= 21) or (age_1 >= 21) 
False                               # 两个都不满足

检查特定值是否包含在列表中

>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']

>>> 'mushrooms' in requested_toppings
True

>>> 'pepperoni' in requested_toppings
False

最简单的if 语句只有一个测试和一个操作

if-else语句

在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作。

检查超过两个条件的情况,往往其中间条件是 由elif引导的

如果你只想执行一个代码块,就使用if-elif-else 结构;如果要运行多个代码块,就使用一系列独立的if 语句。

上一篇 下一篇

猜你喜欢

热点阅读