告别枯燥,60秒学会一个Python小例子。收录整理了42个例子一次性送给大家,希望对大家有所帮助!总有一款适合你~~

一、基本操作

1 链式比较

i = 3
print(1 < i < 3)  # False
print(1 < i <= 3)  # True

2 不用else和if实现计算器

from operator import *def calculator(a, b, k):return {'+': add,'-': sub,'*': mul,'/': truediv,'**': pow}[k](a, b)calculator(1, 2, '+')  # 3
calculator(3, 4, '**')  # 81

3 函数链

from operator import (add, sub)def add_or_sub(a, b, oper):return (add if oper == '+' else sub)(a, b)add_or_sub(1, 2, '-')  # -1

4 求字符串的字节长度

def str_byte_len(mystr):return (len(mystr.encode('utf-8')))str_byte_len('i love python')  # 13(个字节)
str_byte_len('字符')  # 6(个字节)

5 寻找第n次出现位置

def search_n(s, c, n):size = 0for i, x in enumerate(s):if x == c:size += 1if size == n:return ireturn -1print(search_n("fdasadfadf", "a", 3))# 结果为7,正确
print(search_n("fdasadfadf", "a", 30))# 结果为-1,正确

6 去掉最高最低求平均

def score_mean(lst):lst.sort()lst2=lst[1:(len(lst)-1)]return round((sum(lst2)/len(lst2)),2)score_mean([9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]) # 9.07

7 交换元素

def swap(a, b):return b, aswap(1, 0)  # (0,1)

二、基础算法

1 二分搜索

def binarySearch(arr, left, right, x):while left <= right:mid = int(left + (right - left) / 2); # 找到中间位置。求中点写成(left+right)/2更容易溢出,所以不建议这样写# 检查x是否出现在位置midif arr[mid] == x:print('found %d 在索引位置%d 处' %(x,mid))return mid# 假如x更大,则不可能出现在左半部分elif arr[mid] < x:left = mid + 1 #搜索区间变为[mid+1,right]print('区间缩小为[%d,%d]' %(mid+1,right))elif x<arr[mid]:right = mid - 1 #搜索区间变为[left,mid-1]print('区间缩小为[%d,%d]' %(left,mid-1))return -1

2  距离矩阵

x,y = mgrid[0:5,0:5]
list(map(lambda xe,ye: [(ex,ey) for ex, ey in zip(xe, ye)], x,y))
[[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)],[(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)],[(2, 0), (2, 1), (2, 2), (2, 3), (2, 4)],[(3, 0), (3, 1), (3, 2), (3, 3), (3, 4)],[(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]]

三、列表

1 打印乘法表

for i in range(1,10):for j in range(1,i+1):print('{0}*{1}={2}'.format(j,i,j*i),end="\t")print()

结果:

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

2 嵌套数组完全展开

from collections.abc import *def flatten(input_arr, output_arr=None):if output_arr is None:output_arr = []for ele in input_arr:if isinstance(ele, Iterable): # 判断ele是否可迭代flatten(ele, output_arr)  # 尾数递归else:output_arr.append(ele)    # 产生结果return output_arrflatten([[1,2,3],[4,5]], [6,7]) # [6, 7, 1, 2, 3, 4, 5]

3 将list等分为子组

from math import ceildef divide(lst, size):if size <= 0:return [lst]return [lst[i * size:(i+1)*size] for i in range(0, ceil(len(lst) / size))]r = divide([1, 3, 5, 7, 9], 2) # [[1, 3], [5, 7], [9]]

4 生成fibonacci序列前n项

def fibonacci(n):if n <= 1:return [1]fib = [1, 1]while len(fib) < n:fib.append(fib[len(fib) - 1] + fib[len(fib) - 2])return fibfibonacci(5)  # [1, 1, 2, 3, 5]

5 过滤掉各种空值

def filter_false(lst):return list(filter(bool, lst))filter_false([None, 0, False, '', [], 'ok', [1, 2]])# ['ok', [1, 2]]

6 返回列表头元素

def head(lst):return lst[0] if len(lst) > 0 else Nonehead([])  # None
head([3, 4, 1])  # 3

7 返回列表尾元素

def tail(lst):return lst[-1] if len(lst) > 0 else Noneprint(tail([]))  # None
print(tail([3, 4, 1]))  # 1

8 对象转换为可迭代类型

from collections.abc import Iterabledef cast_iterable(val):return val if isinstance(val, Iterable) else [val]cast_iterable('foo')# foo
cast_iterable(12)# [12]
cast_iterable({'foo': 12})# {'foo': 12}

9 求更长列表

def max_length(*lst):return max(*lst, key=lambda v: len(v))r = max_length([1, 2, 3], [4, 5, 6, 7], [8])# [4, 5, 6, 7]

10 出现最多元素

def max_frequency(lst):return max(lst, default='列表为空', key=lambda v: lst.count(v))lst = [1, 3, 3, 2, 1, 1, 2]
max_frequency(lst) # 1

11 求多个列表的最大值

def max_lists(*lst):return max(max(*lst, key=lambda v: max(v)))max_lists([1, 2, 3], [6, 7, 8], [4, 5]) # 8

12 求多个列表的最小值

def min_lists(*lst):return min(min(*lst, key=lambda v: max(v)))min_lists([1, 2, 3], [6, 7, 8], [4, 5]) # 1

13 检查list是否有重复元素

def has_duplicates(lst):return len(lst) == len(set(lst))x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]
y = [1, 2, 3, 4, 5]
has_duplicates(x)  # False
has_duplicates(y)  # True

14 求列表中所有重复元素

from collections import Counterdef find_all_duplicates(lst):c = Counter(lst)return list(filter(lambda k: c[k] > 1, c))find_all_duplicates([1, 2, 2, 3, 3, 3])  # [2,3]

15 列表反转

def reverse(lst):return lst[::-1]reverse([1, -2, 3, 4, 1, 2])# [2, 1, 4, 3, -2, 1]

16 浮点数等差数列

def rang(start, stop, n):start,stop,n = float('%.2f' % start), float('%.2f' % stop),int('%.d' % n)step = (stop-start)/nlst = [start]while n > 0:start,n = start+step,n-1lst.append(round((start), 2))return lstrang(1, 8, 10) # [1.0, 1.7, 2.4, 3.1, 3.8, 4.5, 5.2, 5.9, 6.6, 7.3, 8.0]

四、字典

1 字典值最大的键值对列表

def max_pairs(dic):if len(dic) == 0:return dicmax_val = max(map(lambda v: v[1], dic.items()))return [item for item in dic.items() if item[1] == max_val]max_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})# [('b', 5), ('d', 5)]

2 字典值最小的键值对列表

def min_pairs(dic):if len(dic) == 0:return []min_val = min(map(lambda v: v[1], dic.items()))return [item for item in dic.items() if item[1] == min_val]min_pairs({}) # []r = min_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})
print(r)  # [('b', 5), ('d', 5)]

3 合并两个字典

def merge_dict2(dic1, dic2):return {**dic1, **dic2}  # python3.5后支持的一行代码实现合并字典merge_dict({'a': 1, 'b': 2}, {'c': 3})  # {'a': 1, 'b': 2, 'c': 3}

4 求字典前n个最大值

from heapq import nlargest# 返回字典d前n个最大值对应的键
def topn_dict(d, n):return nlargest(n, d, key=lambda k: d[k])topn_dict({'a': 10, 'b': 8, 'c': 9, 'd': 10}, 3)  # ['a', 'd', 'c']

5 求最小键值对

d={'a':-10,'b':5, 'c':3,'d':5}
min(d.items(),key=lambda x:x[1]) #('a', -10)

五、集合

1 互为变位词

from collections import Counter
# 检查两个字符串是否 相同字母异序词,简称:互为变位词
def anagram(str1, str2):return Counter(str1) == Counter(str2)anagram('eleven+two', 'twelve+one')  # True 这是一对神器的变位词
anagram('eleven', 'twelve')  # False

六、文件操作

1 查找指定文件格式文件

import osdef find_file(work_dir,extension='jpg'):lst = []for filename in os.listdir(work_dir):print(filename)splits = os.path.splitext(filename)ext = splits[1] # 拿到扩展名if ext == '.'+extension:lst.append(filename)return lstfind_file('.','md') # 返回所有目录下的md文件

七、正则和爬虫

1 爬取天气数据并解析温度值

素材来自朋友袁绍

import requests
from lxml import etree
import pandas as pd
import reurl = 'http://www.weather.com.cn/weather1d/101010100.shtml#input'
with requests.get(url) as res:content = res.contenthtml = etree.HTML(content)

通过lxml模块提取值,lxml比beautifulsoup解析在某些场合更高效

location = html.xpath('//*[@id="around"]//a[@target="_blank"]/span/text()')
temperature = html.xpath('//*[@id="around"]/div/ul/li/a/i/text()')

结果:

['香河', '涿州', '唐山', '沧州', '天津', '廊坊', '太原', '石家庄', '涿鹿', '张家口', '保定', '三河', '北京孔庙', '北京国子监', '中国地质博物馆', '月坛公
园', '明城墙遗址公园', '北京市规划展览馆', '什刹海', '南锣鼓巷', '天坛公园', '北海公园', '景山公园', '北京海洋馆']['11/-5°C', '14/-5°C', '12/-6°C', '12/-5°C', '11/-1°C', '11/-5°C', '8/-7°C', '13/-2°C', '8/-6°C', '5/-9°C', '14/-6°C', '11/-4°C', '13/-3°C'
, '13/-3°C', '12/-3°C', '12/-3°C', '13/-3°C', '12/-2°C', '12/-3°C', '13/-3°C', '12/-2°C', '12/-2°C', '12/-2°C', '12/-3°C']
df = pd.DataFrame({'location':location, 'temperature':temperature})
print('温度列')
print(df['temperature'])

正则解析温度值

df['high'] = df['temperature'].apply(lambda x: int(re.match('(-?[0-9]*?)/-?[0-9]*?°C', x).group(1) ) )
df['low'] = df['temperature'].apply(lambda x: int(re.match('-?[0-9]*?/(-?[0-9]*?)°C', x).group(1) ) )
print(df)

详细说明子字符创捕获

除了简单地判断是否匹配之外,正则表达式还有提取子串的强大功能。用()表示的就是要提取的分组(group)。比如:^(\d{3})-(\d{3,8})$分别定义了两个组,可以直接从匹配的字符串中提取出区号和本地号码

m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m.group(0))
print(m.group(1))
print(m.group(2))# 010-12345
# 010
# 12345

如果正则表达式中定义了组,就可以在Match对象上用group()方法提取出子串来。

注意到group(0)永远是原始字符串,group(1)group(2)……表示第1、2、……个子串。

最终结果

Name: temperature, dtype: objectlocation temperature  high  low
0         香河     11/-5°C    11   -5
1         涿州     14/-5°C    14   -5
2         唐山     12/-6°C    12   -6
3         沧州     12/-5°C    12   -5
4         天津     11/-1°C    11   -1
5         廊坊     11/-5°C    11   -5
6         太原      8/-7°C     8   -7
7        石家庄     13/-2°C    13   -2
8         涿鹿      8/-6°C     8   -6
9        张家口      5/-9°C     5   -9
10        保定     14/-6°C    14   -6
11        三河     11/-4°C    11   -4
12      北京孔庙     13/-3°C    13   -3
13     北京国子监     13/-3°C    13   -3
14   中国地质博物馆     12/-3°C    12   -3
15      月坛公园     12/-3°C    12   -3
16   明城墙遗址公园     13/-3°C    13   -3
17  北京市规划展览馆     12/-2°C    12   -2
18       什刹海     12/-3°C    12   -3
19      南锣鼓巷     13/-3°C    13   -3
20      天坛公园     12/-2°C    12   -2
21      北海公园     12/-2°C    12   -2
22      景山公园     12/-2°C    12   -2
23     北京海洋馆     12/-3°C    12   -3

2 批量转化驼峰格式

import re
def camel(s):s = re.sub(r"(\s|_|-)+", " ", s).title().replace(" ", "")return s[0].lower() + s[1:]# 批量转化
def batch_camel(slist):return [camel(s) for s in slist]batch_camel(['student_id', 'student\tname', 'student-add']) #['studentId', 'studentName', 'studentAdd']

八、绘图

1 turtle绘制奥运五环图
结果:

2 turtle绘制漫天雪花
结果:

3 4种不同颜色的色块,它们的颜色真的不同吗?

4 词频云图

import hashlib
import pandas as pd
from wordcloud import WordCloud
geo_data=pd.read_excel(r"../data/geo_data.xlsx")
words = ','.join(x for x in geo_data['city'] if x != []) #筛选出非空列表值
wc = WordCloud(background_color="green", #背景颜色"green"绿色max_words=100, #显示最大词数font_path='./fonts/simhei.ttf', #显示中文min_font_size=5,max_font_size=100,width=500  #图幅宽度)
x = wc.generate(words)
x.to_file('../data/geo_data.png')

八、生成器

1 求斐波那契数列前n项(生成器版)

def fibonacci(n):a, b = 1, 1for _ in range(n):yield aa, b = b, a + blist(fibonacci(5))  # [1, 1, 2, 3, 5]

2 将list等分为子组(生成器版)

from math import ceildef divide_iter(lst, n):if n <= 0:yield lstreturni, div = 0, ceil(len(lst) / n)while i < n:yield lst[i * div: (i + 1) * div]i += 1list(divide_iter([1, 2, 3, 4, 5], 0))  # [[1, 2, 3, 4, 5]]
list(divide_iter([1, 2, 3, 4, 5], 2))  # [[1, 2, 3], [4, 5]]

九、keras

1 Keras入门例子

告别枯燥,60秒学会一个Python小例子。收录整理了42个例子一次性送给大家,希望对大家有所帮助!总有一款适合你~~

一、基本操作

1 链式比较

i = 3
print(1 < i < 3)  # False
print(1 < i <= 3)  # True

2 不用else和if实现计算器

from operator import *def calculator(a, b, k):return {'+': add,'-': sub,'*': mul,'/': truediv,'**': pow}[k](a, b)calculator(1, 2, '+')  # 3
calculator(3, 4, '**')  # 81

3 函数链

from operator import (add, sub)def add_or_sub(a, b, oper):return (add if oper == '+' else sub)(a, b)add_or_sub(1, 2, '-')  # -1

4 求字符串的字节长度

def str_byte_len(mystr):return (len(mystr.encode('utf-8')))str_byte_len('i love python')  # 13(个字节)
str_byte_len('字符')  # 6(个字节)

5 寻找第n次出现位置

def search_n(s, c, n):size = 0for i, x in enumerate(s):if x == c:size += 1if size == n:return ireturn -1print(search_n("fdasadfadf", "a", 3))# 结果为7,正确
print(search_n("fdasadfadf", "a", 30))# 结果为-1,正确

6 去掉最高最低求平均

def score_mean(lst):lst.sort()lst2=lst[1:(len(lst)-1)]return round((sum(lst2)/len(lst2)),2)score_mean([9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]) # 9.07

7 交换元素

def swap(a, b):return b, aswap(1, 0)  # (0,1)

二、基础算法

1 二分搜索

def binarySearch(arr, left, right, x):while left <= right:mid = int(left + (right - left) / 2); # 找到中间位置。求中点写成(left+right)/2更容易溢出,所以不建议这样写# 检查x是否出现在位置midif arr[mid] == x:print('found %d 在索引位置%d 处' %(x,mid))return mid# 假如x更大,则不可能出现在左半部分elif arr[mid] < x:left = mid + 1 #搜索区间变为[mid+1,right]print('区间缩小为[%d,%d]' %(mid+1,right))elif x<arr[mid]:right = mid - 1 #搜索区间变为[left,mid-1]print('区间缩小为[%d,%d]' %(left,mid-1))return -1

2  距离矩阵

x,y = mgrid[0:5,0:5]
list(map(lambda xe,ye: [(ex,ey) for ex, ey in zip(xe, ye)], x,y))
[[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)],[(1, 0), (1, 1), (1, 2), (1, 3), (1, 4)],[(2, 0), (2, 1), (2, 2), (2, 3), (2, 4)],[(3, 0), (3, 1), (3, 2), (3, 3), (3, 4)],[(4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]]

三、列表

1 打印乘法表

for i in range(1,10):for j in range(1,i+1):print('{0}*{1}={2}'.format(j,i,j*i),end="\t")print()

结果:

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

2 嵌套数组完全展开

from collections.abc import *def flatten(input_arr, output_arr=None):if output_arr is None:output_arr = []for ele in input_arr:if isinstance(ele, Iterable): # 判断ele是否可迭代flatten(ele, output_arr)  # 尾数递归else:output_arr.append(ele)    # 产生结果return output_arrflatten([[1,2,3],[4,5]], [6,7]) # [6, 7, 1, 2, 3, 4, 5]

3 将list等分为子组

from math import ceildef divide(lst, size):if size <= 0:return [lst]return [lst[i * size:(i+1)*size] for i in range(0, ceil(len(lst) / size))]r = divide([1, 3, 5, 7, 9], 2) # [[1, 3], [5, 7], [9]]

4 生成fibonacci序列前n项

def fibonacci(n):if n <= 1:return [1]fib = [1, 1]while len(fib) < n:fib.append(fib[len(fib) - 1] + fib[len(fib) - 2])return fibfibonacci(5)  # [1, 1, 2, 3, 5]

5 过滤掉各种空值

def filter_false(lst):return list(filter(bool, lst))filter_false([None, 0, False, '', [], 'ok', [1, 2]])# ['ok', [1, 2]]

6 返回列表头元素

def head(lst):return lst[0] if len(lst) > 0 else Nonehead([])  # None
head([3, 4, 1])  # 3

7 返回列表尾元素

def tail(lst):return lst[-1] if len(lst) > 0 else Noneprint(tail([]))  # None
print(tail([3, 4, 1]))  # 1

8 对象转换为可迭代类型

from collections.abc import Iterabledef cast_iterable(val):return val if isinstance(val, Iterable) else [val]cast_iterable('foo')# foo
cast_iterable(12)# [12]
cast_iterable({'foo': 12})# {'foo': 12}

9 求更长列表

def max_length(*lst):return max(*lst, key=lambda v: len(v))r = max_length([1, 2, 3], [4, 5, 6, 7], [8])# [4, 5, 6, 7]

10 出现最多元素

def max_frequency(lst):return max(lst, default='列表为空', key=lambda v: lst.count(v))lst = [1, 3, 3, 2, 1, 1, 2]
max_frequency(lst) # 1

11 求多个列表的最大值

def max_lists(*lst):return max(max(*lst, key=lambda v: max(v)))max_lists([1, 2, 3], [6, 7, 8], [4, 5]) # 8

12 求多个列表的最小值

def min_lists(*lst):return min(min(*lst, key=lambda v: max(v)))min_lists([1, 2, 3], [6, 7, 8], [4, 5]) # 1

13 检查list是否有重复元素

def has_duplicates(lst):return len(lst) == len(set(lst))x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]
y = [1, 2, 3, 4, 5]
has_duplicates(x)  # False
has_duplicates(y)  # True

14 求列表中所有重复元素

from collections import Counterdef find_all_duplicates(lst):c = Counter(lst)return list(filter(lambda k: c[k] > 1, c))find_all_duplicates([1, 2, 2, 3, 3, 3])  # [2,3]

15 列表反转

def reverse(lst):return lst[::-1]reverse([1, -2, 3, 4, 1, 2])# [2, 1, 4, 3, -2, 1]

16 浮点数等差数列

def rang(start, stop, n):start,stop,n = float('%.2f' % start), float('%.2f' % stop),int('%.d' % n)step = (stop-start)/nlst = [start]while n > 0:start,n = start+step,n-1lst.append(round((start), 2))return lstrang(1, 8, 10) # [1.0, 1.7, 2.4, 3.1, 3.8, 4.5, 5.2, 5.9, 6.6, 7.3, 8.0]

四、字典

1 字典值最大的键值对列表

def max_pairs(dic):if len(dic) == 0:return dicmax_val = max(map(lambda v: v[1], dic.items()))return [item for item in dic.items() if item[1] == max_val]max_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})# [('b', 5), ('d', 5)]

2 字典值最小的键值对列表

def min_pairs(dic):if len(dic) == 0:return []min_val = min(map(lambda v: v[1], dic.items()))return [item for item in dic.items() if item[1] == min_val]min_pairs({}) # []r = min_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})
print(r)  # [('b', 5), ('d', 5)]

3 合并两个字典

def merge_dict2(dic1, dic2):return {**dic1, **dic2}  # python3.5后支持的一行代码实现合并字典merge_dict({'a': 1, 'b': 2}, {'c': 3})  # {'a': 1, 'b': 2, 'c': 3}

4 求字典前n个最大值

from heapq import nlargest# 返回字典d前n个最大值对应的键
def topn_dict(d, n):return nlargest(n, d, key=lambda k: d[k])topn_dict({'a': 10, 'b': 8, 'c': 9, 'd': 10}, 3)  # ['a', 'd', 'c']

5 求最小键值对

d={'a':-10,'b':5, 'c':3,'d':5}
min(d.items(),key=lambda x:x[1]) #('a', -10)

五、集合

1 互为变位词

from collections import Counter
# 检查两个字符串是否 相同字母异序词,简称:互为变位词
def anagram(str1, str2):return Counter(str1) == Counter(str2)anagram('eleven+two', 'twelve+one')  # True 这是一对神器的变位词
anagram('eleven', 'twelve')  # False

六、文件操作

1 查找指定文件格式文件

import osdef find_file(work_dir,extension='jpg'):lst = []for filename in os.listdir(work_dir):print(filename)splits = os.path.splitext(filename)ext = splits[1] # 拿到扩展名if ext == '.'+extension:lst.append(filename)return lstfind_file('.','md') # 返回所有目录下的md文件

七、正则和爬虫

1 爬取天气数据并解析温度值

素材来自朋友袁绍

import requests
from lxml import etree
import pandas as pd
import reurl = 'http://www.weather.com.cn/weather1d/101010100.shtml#input'
with requests.get(url) as res:content = res.contenthtml = etree.HTML(content)

通过lxml模块提取值,lxml比beautifulsoup解析在某些场合更高效

location = html.xpath('//*[@id="around"]//a[@target="_blank"]/span/text()')
temperature = html.xpath('//*[@id="around"]/div/ul/li/a/i/text()')

结果:

['香河', '涿州', '唐山', '沧州', '天津', '廊坊', '太原', '石家庄', '涿鹿', '张家口', '保定', '三河', '北京孔庙', '北京国子监', '中国地质博物馆', '月坛公
园', '明城墙遗址公园', '北京市规划展览馆', '什刹海', '南锣鼓巷', '天坛公园', '北海公园', '景山公园', '北京海洋馆']['11/-5°C', '14/-5°C', '12/-6°C', '12/-5°C', '11/-1°C', '11/-5°C', '8/-7°C', '13/-2°C', '8/-6°C', '5/-9°C', '14/-6°C', '11/-4°C', '13/-3°C'
, '13/-3°C', '12/-3°C', '12/-3°C', '13/-3°C', '12/-2°C', '12/-3°C', '13/-3°C', '12/-2°C', '12/-2°C', '12/-2°C', '12/-3°C']
df = pd.DataFrame({'location':location, 'temperature':temperature})
print('温度列')
print(df['temperature'])

正则解析温度值

df['high'] = df['temperature'].apply(lambda x: int(re.match('(-?[0-9]*?)/-?[0-9]*?°C', x).group(1) ) )
df['low'] = df['temperature'].apply(lambda x: int(re.match('-?[0-9]*?/(-?[0-9]*?)°C', x).group(1) ) )
print(df)

详细说明子字符创捕获

除了简单地判断是否匹配之外,正则表达式还有提取子串的强大功能。用()表示的就是要提取的分组(group)。比如:^(\d{3})-(\d{3,8})$分别定义了两个组,可以直接从匹配的字符串中提取出区号和本地号码

m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m.group(0))
print(m.group(1))
print(m.group(2))# 010-12345
# 010
# 12345

如果正则表达式中定义了组,就可以在Match对象上用group()方法提取出子串来。

注意到group(0)永远是原始字符串,group(1)group(2)……表示第1、2、……个子串。

最终结果

Name: temperature, dtype: objectlocation temperature  high  low
0         香河     11/-5°C    11   -5
1         涿州     14/-5°C    14   -5
2         唐山     12/-6°C    12   -6
3         沧州     12/-5°C    12   -5
4         天津     11/-1°C    11   -1
5         廊坊     11/-5°C    11   -5
6         太原      8/-7°C     8   -7
7        石家庄     13/-2°C    13   -2
8         涿鹿      8/-6°C     8   -6
9        张家口      5/-9°C     5   -9
10        保定     14/-6°C    14   -6
11        三河     11/-4°C    11   -4
12      北京孔庙     13/-3°C    13   -3
13     北京国子监     13/-3°C    13   -3
14   中国地质博物馆     12/-3°C    12   -3
15      月坛公园     12/-3°C    12   -3
16   明城墙遗址公园     13/-3°C    13   -3
17  北京市规划展览馆     12/-2°C    12   -2
18       什刹海     12/-3°C    12   -3
19      南锣鼓巷     13/-3°C    13   -3
20      天坛公园     12/-2°C    12   -2
21      北海公园     12/-2°C    12   -2
22      景山公园     12/-2°C    12   -2
23     北京海洋馆     12/-3°C    12   -3

2 批量转化驼峰格式

import re
def camel(s):s = re.sub(r"(\s|_|-)+", " ", s).title().replace(" ", "")return s[0].lower() + s[1:]# 批量转化
def batch_camel(slist):return [camel(s) for s in slist]batch_camel(['student_id', 'student\tname', 'student-add']) #['studentId', 'studentName', 'studentAdd']

八、绘图

1 turtle绘制奥运五环图
结果:

2 turtle绘制漫天雪花
结果:

3 4种不同颜色的色块,它们的颜色真的不同吗?

4 词频云图

import hashlib
import pandas as pd
from wordcloud import WordCloud
geo_data=pd.read_excel(r"../data/geo_data.xlsx")
words = ','.join(x for x in geo_data['city'] if x != []) #筛选出非空列表值
wc = WordCloud(background_color="green", #背景颜色"green"绿色max_words=100, #显示最大词数font_path='./fonts/simhei.ttf', #显示中文min_font_size=5,max_font_size=100,width=500  #图幅宽度)
x = wc.generate(words)
x.to_file('../data/geo_data.png')

八、生成器

1 求斐波那契数列前n项(生成器版)

def fibonacci(n):a, b = 1, 1for _ in range(n):yield aa, b = b, a + blist(fibonacci(5))  # [1, 1, 2, 3, 5]

2 将list等分为子组(生成器版)

from math import ceildef divide_iter(lst, n):if n <= 0:yield lstreturni, div = 0, ceil(len(lst) / n)while i < n:yield lst[i * div: (i + 1) * div]i += 1list(divide_iter([1, 2, 3, 4, 5], 0))  # [[1, 2, 3, 4, 5]]
list(divide_iter([1, 2, 3, 4, 5], 2))  # [[1, 2, 3], [4, 5]]

九、keras

1 Keras入门例子

import numpy as np
from keras.models import Sequential
from keras.layers import Densedata = np.random.random((1000, 1000))
labels = np.random.randint(2, size=(1000, 1))
model = Sequential()
model.add(Dense(32,activation='relu',input_dim=100))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimize='rmsprop', loss='binary_crossentropy',metrics=['accuracy'])
model.fit(data, labels, epochs=10, batch_size=32)
predictions = model.predict(data)

python经典练习题汇总相关推荐

  1. c语言刘备关羽张飞的编程题,《三国演义》经典练习题汇总含参考答案

    <三国演义>经典练习题汇总含参考答案 一.填空 1.<三国演义>的作者是()代的(),本书与().().()合称"四大名著". 4."滚滚长江东逝 ...

  2. python中输出n开始的5个奇数_送你99道Python经典练习题,练完直接上手做项目,免费送了来拿吧...

    学python没练习题怎么行.今天,给大家准备一个项目: 99道编程练习,这些题如果能坚持每天至少完成一道,一定可以帮大家轻松 get Python 的编程技能.目前,这个项目已经获得了 2924 S ...

  3. python 经典练习题一

    突然有一个想法,把自己练习过,及想要练习的题目或项目,发出来,一起来练习哇,先从Python基础知识开始,每天5道练习题,目前一共105道练习题,通过21天练习巩固Python的基础知识,来提升自己的 ...

  4. Python面向对象练习题汇总

    1. 什么是类,什么是对象? 类:对一类事物的描述,是抽象的.概念上的定义. 对象:实际存在的该类事物的每个个体,因而也称实例(instance). 类是对象的抽象,对象是类的实例. 2. pytho ...

  5. Python经典练习题——求水仙花数

    严格来说,我并不知道何谓"水仙花数",因为以前读书时根本没听过这种数,也不知道这种数有什么特征.后来从事编程之后反而听说了所谓的"水仙花数". 如果通过网络查询 ...

  6. python经典练习题

    ''' for i in range(10):x=int(input('输入任意整数:'))if x>100:print(x,'大于100')elif x<=0:print(x,'小于0' ...

  7. 字典 选取前100_100道 Python 经典练习题004

    题目:输入某年某月某日,判断这一天是这一年的第几天? 这道题看似简单,但实际要考虑的问题很多.首先我们要判断平年/闰年,因为它涉及到2月是否会多一天的问题:另外我们还要判断用户的每一个输入是否合法,不 ...

  8. 【python经典练习题100-试题6】打印字母C H

    题目: 用*号输出字母C的图案 源代码: print('用*号输出字母C的图案!') print(' '*5,'*'*6) print(' '*2,'*'*3) print('*'*2) print( ...

  9. 100道python经典练习题

    链接:https://pan.baidu.com/s/1K0iuZKJukLoGQ8OBy7xq1Q 提取码:2s6q 链接长期有效,如有疑问,欢迎评论区交流.

  10. python企业发放的奖金根据利润提成_100 道 Python 经典练习题002

    题目:企业发放的奖金根据利润提成.利润(I)低于或等于10万元时,奖金可提10%:利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%:20万到40万 ...

最新文章

  1. 洛谷P1311 选择客栈
  2. 鹅厂开源先锋,日均计算量超30万亿,全力打破数据墙
  3. 解读 2018之Go语言篇(下):明年有哪些值得期待?
  4. 现在ui设计出来好找工作吗?
  5. 百度下mysql卸载_如何把Mysql卸载干净(亲测有效)
  6. 广州新一代域名注册量动态:11月下旬净增3425个
  7. 一起来看小米发布会!
  8. VS的一个项目,release/debug/x64/win32的设置有没有办法一次设置?
  9. 关于医学影像中的轴位面(横断面)、冠状面、矢状面的解释
  10. 输入汉字,自动转成汉语拼音。。。
  11. 一些方便的LaTex在线编辑工具
  12. 真人qq秀代码_关于QQ我的记忆
  13. android 下的 WATCHDOG(2)
  14. Hadoop生态系统功能组件,主要包括哪些?
  15. 主流深度学习CTR模型
  16. 解决在uniapp项目中小程序调用获取微信绑定手机号
  17. python类初始化返回实例_Python基础——类、实例及初始化
  18. 自动化软件测试工程师(初面)面试题解析(含答案)
  19. (社会舆情) 小世界网络,规则网络,随机网络
  20. MySQL简介以及简单的下载和安装

热门文章

  1. java导出word图片格式_Java 导出带图片和列表的 Word
  2. 命令行下载网页视频方法
  3. 远程高效办公指南,每天都是能量满满的workaholism!
  4. 英文字体识别在线识别_如何查找和识别字体
  5. arcgis的重采样和插值方法
  6. 漫谈Anchor-based和Anchor-Free
  7. 大学生数学竞赛试题荟萃 (更新至2017年10月28日)
  8. Excel的Match函数详解
  9. ZFS的ashift参数解读
  10. 【教程】在线生成LaTeX中的表格