切片、迭代、列表生成式

2018-10-28  本文已影响0人  C_Fei

切片

用于取list或tuple部分元素的操作


切片操作符用法: list[m,n]可以取到list中的第m个元素到第n-1个元素,若m=0,即从第1个元素开始取,m可省略,即为list[:n];若n=len(list),即从最后一个元素开始取,n可省略,即为list[m:];m还可以为负数,比如list[-2:]取的是最后两个数(因为最后一个数是-1)
  list[m:n:p],指的是从m开始,相隔p个元素取一个元素,一直到第n个元素

L=['q','w','e','r','t','y']
print(L[1:3])
//输出为['w', 'e']
L=list(range(100))
print(L[:20:5])
//输出为[0, 5, 10, 15]
print('qwertyuio'[2:6])
//输出为   erty

迭代

迭代就是遍历list、tuple、dict等,简单点就是for循环嘛

//遍历list
L=['q','w','e','r','t','y']
for x in L:
    print(x)
L={'a':1,'b':2,'c':3,'d':4}
for key in L:
    print(key)
//输出为  a/n  b/n  c/n   d/n
 for ch in 'ABCDEFG':
    print(ch)

怎么判断一个对象是否可以迭代呢?
通过 collections 模块的 Iterable 类型判断

from collections import Iterable
print(isinstance('abc', Iterable))#输出为True
print(isinstance(12345, Iterable))#输出为False

怎么同时迭代循环一个list的索引和元素?
Python 内置的 enumerate 函数可以把一个 list 变成索引-元素对

for i,value in enumerate(['1','2','3','4']):
    print(i,value)
#0 1
#1 2
#2 3
#3 4


列表生成式

如何生成list[1x1, 2x2, 3x3, ..., 10x10]?

print([x*x for x in range(1,11)])
#输出为   [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print([x*x for x in range(1,11) if x%2==0])
#输出为   [4, 16, 36, 64, 100]

还可以使用两层for循环生成它的全排列

print([m+n for m in '123'for n in'qw'])
#输出为['1q', '1w', '2q', '2w', '3q', '3w']

怎么把一个 list 中所有的字符串变成小写?

L = ['Hello', 'World', 'IBM', 'Apple']
print([s.lower() for s in L])
#输出为  ['hello', 'world', 'ibm', 'apple']

练习:
L1 = ['Hello', 'World', 18, 'Apple', None] ,输出L2= ['hello', 'world', 'apple']
提示:使用内建的 isinstance 函数可以判断一个变量是不是字符串

L1=['Hello', 'World', 18, 'Apple', None]
L2=[s.lower() for s in L1 if isinstance(s, str)]
print(L2)
上一篇下一篇

猜你喜欢

热点阅读