首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

人生苦短,我用python之入门篇-3

接入门篇-2

5 函数

内置函数可以直接使用,不需要导入

5.1 斐波那契数列

输入

# def fib(n): # write Fibonacci series up to n

# """Print a Fibonacci series up to n"""

# a, b = 0, 1

# while a

# print(a)

# a, b = b, a+b

def fib2(n): # return Fibonacci series up to n

"""Return a list containing the Fibonacci series up to n"""

result = []

a, b = 0, 1

while a

result.append(a) # see below

a, b = b, a+b

return result

# fib(100)

fib2(100)

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

输出

5.2 自定义实现trim函数

输入

def dif_trim(str):

if str[:1] !=' ' and str[-1:] !=' ':

return str

elif str[:1] ==' ': #左边有空格

return dif_trim(str[1:]) #迭代

else: #右边有空格

return dif_trim(str[:-1])

ns=' 222 33 '

print(ns)

dif_trim(ns)

'222 33'

输出

5.3 map函数

输入

def f(x):

t=x-2

return t

l1=[1,2,3]

map(f,l1)

# map?

map(str,[1,2,3])

# map(str.lower,['a','B','c'])

# map(str.lower,'abCdeF')

# map(round,[1.2,3.5]) #把一列变量应用到一个函数上,并返回结果

['1', '2', '3']

输出

输入

map(str,[1,2,3])

['1', '2', '3']

输出

5.4 reduce函数

输入

from functools import reduce

def fn(x, y):

return x * 10 + y

def char2num(s):

digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

return digits[s]

map(char2num, '13579')

# reduce(fn, map(char2num, '13579'))

[1, 3, 5, 7, 9]

输出

6 获取数据

# import pyspark.sql as ss

#spark= ss.SparkSession.builder.appName("zhaosr_pyspark").enableHiveSupport().getOrCreate()

# spark.stop()

sql1='select * from dw_god_d_msk_service where p_date =20180416'

msk_service =spark.sql(sql1)

输入

msk_service.columns

msk_service.count()

400649

输出

7 python语言特性案例

输入

d = {}

with file('text.txt') as fp: #with as 实际上执行了打开文件、读取数据到变量、关闭文件。

for line in fp: #fp是可迭代对象

words = line.split() #line是文本行,str型.split为str类型自身的函数。

for word in words:

d[word] = d.get(word, 0) + 1 #循环累计。get方法dict类型是通过key得到value的方法。

for k, v in d.iteritems(): #iteritems是dict类型获取key和value对的方法。

print k, v

ok 4

I 2

am 2

are 2

not 1

you 2

输出

输入

#python读取的文件为可迭代对象,可按行读取数据

# from collections import Iterable

# isinstance(fp, Iterable) # str是否可迭代

True

输出

输入

#如果不使用with as 打开文件,就需要以下步骤

# file_test = open("text.txt")

# print file_test.next()

# print file_test.seek(0)

# print file_test.readline()

# file_test.close()

# file_test

# 'a :b,c;d'.split(',')

['a :b', 'c;d']

输出

下一节将从实例开始!

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180803G0IXPF00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券