1.例题答案:小写化含有数字的list
L1 = ['Hello','World',18,'Apple',None]
L2 = [s.lower() for s in L1 if isinstance(s,str) == True]
[L2.insert(key,value) for key,value in enumerate(L1) if isinstance(value,int) == True ]
>>>L2
['hello', 'world', 18, 'apple']
注意
enumerate() 将list转化为 索引-元素 对,然后可以使用类似于dict的方法读取下标和元素。
isintance() 判断字符str,判断数字int \ float
dict 索引-元素 对 的读取要使用dict.items()
list 指定位置添加字符:list.insert(下标,元素)
格式如下,
[x*x for x in range(1,11) if x%2 == 0]
x*x是f(x),x是自变量,if后的是条件,range(1,11)是定义域,结果是值域
2.
for循环可以是下标,也可以是对象。和C++不同。
3.
切片的格式
list[::2] 每两个取一
list[::] 赋值所有元素
list[1:10] 取第1到10的元素
list / tuple / 字符串 都可切片
4.例题答案:杨辉三角(没把握)
# -*- coding: utf-8 -*-
def triangle(L = []):
L.insert(0,0)
L.append(0)
length = len(L) - 1
L1 = list(range(length))
for i in range(length):
L1[i] = L[i] + L[i+1]
yield L1
调用过程:
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
========================== RESTART: D:\triangle.py ==========================
>>> next(triangle([1]))
[1, 1]
>>> next(triangle([1,1]))
[1, 2, 1]
>>> next(triangle([1,2,1]))
[1, 3, 3, 1]
>>> next(triangle([1,3,3,1]))
[1, 4, 6, 4, 1]
>>> next(triangle([1, 4, 6, 4, 1]))
[1, 5, 10, 10, 5, 1]
>>>