0%

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 序列求和
print(sum([1,2,3,4,5,6,7,8,9,]))
# sum函数的原型是sum(iterable,start).可以设置一个初始值
print(sum([1,2,3,4,5,6,7,8,9,],5))
# 展开2层的嵌套列表
iterable = [[1,2],[3,4],[5,6],[7,8]]
print(sum(iterable,[0]))# 后面的start可以为空
# sum函数与下列函数等效
start = [0]
for element in iterable:
start += element
print(start)
start = [0]
# sum 函数可以看作reduce()的特殊情况
from functools import reduce
from operator import add
print(reduce(add,iterable,start))

分支结构

if

switch

语法结构

1
2
3
4
5
6
7
switch (表达式) { case1:
语句组1 case2:
语句组2 case3:
语句组3 ...
case 判断值n: 语句组n
default: 语句组n+1
}

switch语句中“表达式”计算结果只能是int,byte,short,char类型,不能是long更不能是其他的类型。

循环结构

while

do-while

for

for-each语句

Java 5之后提供了一种专门用于遍历集合的for循环——for-each循环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Test {
public static void main (String[]args) {

int[ ]numbers = {1,3,5,7,9};
System.out.printf("for-each 语句%n");
for (int number : numbers) {
System.out.printf("%d%n",number);
}
}
}
/*
* 输出结果:
*
for-each 语句
1
3
5
7
9
*/

跳转语句

跳转语句能够改变程序的执行顺序,可以实现程序的跳转。

break

break;不带标签

break label;带标签

默认情况下,break只会跳出最近的内循环。如果要跳出代码第1行的外循环, 可以为外循环添加一个标签,注意在定义标签的时候后面跟一个冒号

添加标签对于多层嵌套循环是很有必要的,适 当使用可以提高程序的执行效率。

continue

带标签

不带标签

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package nianchu;

public class Test {
public static void main (String[]args) {
int a=5,b=2;
x1:for(a=0;a<3;a++) {
for(b=0;b<3;b++) {
if(a==b) {
continue x1;
}
System.out.printf("(%d,%d)",a,b);
}
}

}
}
/*
* 输出结果:
*
(1,0)(2,0)(2,1)
*/

小技巧

输出时可以用+号将要输出的两部分连在一起

实例:

1
2
3
4
5
public class Test {
public static void main (String[]args) {
System.out.println("C" + "LOVE" + "L");
}
}

获取数组的长度

numbers.length

1
printf主要是继承了C语言的printf的一些特性,可以进行格式化输出
1
print就是一般的标准输出,但是不换行
1
println和print基本没什么差别,就是最后会换行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package nianchu;

public class Test {
public static void main (String[]args) {
int i = 0,j = 0;
for(i= 1;i <= 9;i++) {
for(j=1;j<=i;j++) {
System.out.printf("%d*%d=%d",j,i,j*i);
System.out.printf(" ");
if(j==i) {
System.out.printf("%n");
}
}
}

}
}
/*
* 输出结果:
*
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
*/

描述

给定一个数字列表,返回其所有可能的排列。

样例

样例 1:

1
2
3
4
5
输入:[1]
输出:
[
[1]
]

样例 2:

1
2
3
4
5
6
7
8
9
10
输入:[1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import itertools
class Solution:
"""
@param: nums: A list of integers.
@return: A list of permutations.
"""
def permute(self, nums):
pailie = list(itertools.permutations(nums)) # 要list一下,不然它只是一个对象

return pailie



so = Solution()
print(so.permute([1,2,3]))

22. 列表扁平化

给定一个列表,该列表中的每个元素要么是个列表,要么是整数。将其变成一个只包含整数的简单列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution(object):

# @param nestedList a list, each element in the list
# can be a list or integer, for example [1,2,[1,2]]
# @return {int[]} a list of integer
def flatten(self, nestedList):
a = []
for i in range(len(nestedList)):#用于判断给定列表中的元素是否含有列表(注:这一目的主要是为了结束递归的死循环)
if type(nestedList[i]) == list:#如果有就将列表中的列表分别取出来放到新的列表中
for j in range(len(nestedList)):
if type(nestedList[j]) != list:
a.append(nestedList[j])
else:
for k in range(len(nestedList[j])):
a.append((nestedList[j])[k])
return Solution.flatten(self,a)#使用递归完成多次“套娃”的情况

return nestedList#如果没有就直接返回这个列表



nums = [4,[3,[2,[1]]]]
so = Solution()
print(so.flatten(nums))

"""
输出结果:
[4, 3, 2, 1]
"""

描述

给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution:
"""
@param nums: The integer array.
@param target: Target to find.
@return: The first position of target. Position starts from 0.
"""
def binarySearch(self, nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] == target:
while(mid >= 0):#新增加的while和if用于解决有重复数字的情况,并保证每次都输出第一次出现的target的下标
if nums[mid] != target:
break

mid = mid - 1
if mid <= -1:
return 0
return mid + 1#多减了一次,所以输出时+1
elif target > nums[mid]:
low = mid + 1
else:
high = mid - 1

return -1



nums = [4,5,9,12,13,14,15,15,18]
so = Solution()
print(so.binarySearch(nums,9))

说明:

Python内置的itertools模块中包含了一系列用来产生不同款类型迭代器的函数和类,这些函数的返回值都是一个迭代器。

迭代器函数类型

无限迭代器:生成一个无限序列,比如自然序列1,2,3,4…;

有限迭代器:接受一个或多个序列作为参数,进行组合、分组和过滤

组合生成器:序列的排列、组合,求序列的笛卡尔积等

无限迭代器

组合生成器

product: product用于求多个可迭代对象的组合,它跟嵌套的for循环等价。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
j = 0
for i in itertools.product("12345","ABCDE"):
print(i,end='')
j = j+1


print("")
print("一共有{}种组合".format(j))

"""
输出结果为:
('1', 'A')('1', 'B')('1', 'C')('1', 'D')('1', 'E')('2', 'A')('2', 'B')('2', 'C')('2', 'D')('2', 'E')('3', 'A')('3', 'B')('3', 'C')('3', 'D')('3', 'E')('4', 'A')('4', 'B')('4', 'C')('4', 'D')('4', 'E')('5', 'A')('5', 'B')('5', 'C')('5', 'D')('5', 'E')
一共有25种组合

"""

permutations: 用于生成一个全排列

1
2
3
4
5
6
nums = [1,2,3,4]
print(list(itertools.permutations(nums)))

"""输出结果:
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
"""

combinations:用于求序列的组合

1
2
3
4
5
6
7
nums = [1,2,3,4]
print(list(itertools.combinations(nums,2)))
"""
输出结果:

[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
"""

⚠️注意区分product、permutations和combinations的区别

技巧

sorted()方法——可用于给字符串排序,通常是按照字母表的顺序

1
2
3
4
5
6
7
8
a = "fadsfga"
print(sorted(a))

"""输出结果:
['a', 'a', 'd', 'f', 'f', 'g', 's']


"""

count()方法

1
2
3
4
5
6
7
a = 'fnsadfgdsgsadfdsa'
b = a.count('f')
print(b)
"""
输出结果:
3
"""

ord()函数

1
2
3
4
5
6
7
8
9
10
## ord()函数# ord() 函数以一个字符作为参数,返回参数对应的 ASCII 数值,便于和后面捕捉的键位关联

print(ord('a'))
print(ord('A'))

"""
输出结果:
97
65
"""

二元、三元表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
## 二元表达式

init = 1

number = 100 if init else 0

print(number)

##三元表达
wide= -1

new_w = 299 if wide>0 else 'sdf' if wide==0 else 28
print(new_w)
"""
输出结果

100
28
"""

randrange——获取指定范围内的随机数

1
2
3
## randrange---给定一个范围,获取范围之内的随机数
import random
print(random.randrange(100))

enumerate()函数

1
2
3
4
5
6
7
8
'''enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,
'''
names = 'chenqiaochu'
for key, value in enumerate(names):
print(key,value)

'''output:
'''

小知识

Python不能直接将包含小数点的字符串’1127437398.85751’ 转换为整数

关于字典键值对的输入

1
2
3
4
5
6
7
a = {'name' : '重庆','mather' : 'China' }
for key in a.keys():
print(key, a[key])
'''输出结果:
name 重庆
mather China
'''

关于字典

键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行。

字典内置函数总结:

1.cmp(dict1,dict2):比较两个元素

(比较方法见:)

https://blog.csdn.net/b_11111/article/details/52830590

2.len()计算字典元素个数,即键的总数

3.str()输出字典可打印的字符串表示

4.type返回变量的类型,如果变量是字典就返回字典类型

字典内置方法总结:

1.clear删除字典内的所有元素

2.copy返回一个字典的浅复制

3.fromkeys(sep,[,val]):创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值

4.get(key)返回指定键的值,如果值不在字典中就返回None

5.has_key(key)如果键在字典dict中返回true,否则返回flase

6.items:以列表返回可遍历的(键值对)元组数组

7.keys:以列表返回一个字典所有的键

8.values:以列表返回字典中的所有值

9.update(dice2):把字典dict2中键值对更新到dict中

10.pop:删除给定键key所对应的值,也一同删除了键,返回值为被删除的值

11.popitem:返回并删除字典中最后一对键和值

用字典中的元素创建一个新的字典

1
2
3
4
5
6
7
8
9
10
11
12
dicts = {}
dicts['first'] = "china"
dicts['lover'] = 'chongqing'
# 用列表中的元素重新创建一个新列表
dicts1 = {}
print(dicts['first'])
dicts1 = {'a':dicts['first'],'b':dicts['lover']}
print(dicts1)
'''
输出结果:
{'a': 'chenqiaochu', 'b': 'leibowen'}
'''

变量可以指向函数

1
2
3
4
5
6
f = abs
print(f(-100))
"""
输出结果:
100
"""

函数名其实就是指向函数的变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
abs =10
print(abs)
print(abs(-200))

"""
输出结果:
10
Traceback (most recent call last):
File "/Users/bowenkei/Desktop/Python/项目2-数据可视化/test.py", line 3, in <module>
print(abs(-200))
TypeError: 'int' object is not callable

"""
# 有结果可以看出,此时abs已经失去了原有函数的意思了

传入函数

既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
# 最简单的高阶函数
# 一个最简单的高阶函数
def add(x,y,f):
return (f(x)+f(y))


print(add(500,20,abs))

"""
输出结果:
520

"""

编写高阶函数,就是让函数的参数能够接收别的函数。

把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。

字符串操作

capitalize()函数 - 将字符串改为首位大写其余小写

title()函数 - 将字符串改为每个单词都是首字母大写其余小写份形式

比较字符串

描述

比较两个字符串A和B,确定A中是否包含B中所有的字符。字符串A和B中的字符都是 大写字母

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
"""
@param A: A string
@param B: A string
@return: if string A contains all of the characters in B return true else return false
"""
def compareStrings(self, A, B):
# write your code here
#此题采用了反向思维的方法,通过举出返回Flase的几种情况后,其余都是True

if len(A) < len(B):
return False
if len(A) == len(B):
return(sorted(A) == sorted(B))
for i in B:
if A.count(i) < B.count(i):
return False
return True

13.字符串查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
"""
@param source:
@param target:
@return: return the index
"""
def strStr(self, source, target):
geshu=0
a = len(source)
b = len(target)
if source =="" and target =="":#排除特殊情况
return 0
elif source !="" and target =="":#继续排除特殊情况
return 0
elif target not in source:#被查找字符串不在已知字符串的情况
return -1
else:#需要返回第一个出现位置的情况
for i in range(a):
if target[0] == source[i]:
for j in range(b):
if (i+j) < a:#避免字符串索引溢出
if source[i+j] == target[j]:
geshu = geshu + 1

if geshu == b:
return i

so = Solution()
print(so.strStr("tartarget","target"))