1、python的数据结构

本文详细介绍了Python编程的基础知识,包括字符串与时间的转换、for循环、数据结构如元组、字典和集合的操作方法,以及高级特性如列表推导式、函数列表、匿名函数lambda、生成器、高阶函数等。

本人工作环境安装的是anaconda(包含第三方的库,此处略过)

字符串和元组是不可变的

字符串与时间的转换:

from datetime import datetime

if __name__ == '__main__':
    dt = datetime(2016,12,3,11,12,13)
    print type(dt.day)
    print dt.strftime('%Y%m%d')
    #类型为datetime.datetime
    print datetime.strptime('20120110','%Y%m%d')

运行结果:

C:\Anaconda2\python.exe E:/scp/com/lenovo/scp/test01.py
<type 'int'>
20161203
2012-01-10 00:00:00

Process finished with exit code 0

for循环

for  item  in  collection

python 中没有  ++  --  没有空代码块(可以使用pass代替)

range() 和xrange()  都是生成列表,但是xrange()效率高

python 数据结构

元组

字典 dict:

# -*- coding: utf-8 -*-

if __name__ == '__main__':
    # ll = [1,2,3]
    # print tuple(ll)
    #     列表
    empty_dict = {}
    dict1 = {'a':1,'b':2,'c':[1,2,3]}
    print empty_dict
    print dict1
    dict1['d']=12
    print dict1
    pop = dict1.pop('d')
    print pop
    print dict1
    print dict1.keys()
    print dict1.values()
    # 合并字典(如果有,替换,没有添加新的元素)
    dict2 = {'a':'a','4':"aaa",'5':'dfdf'}
    dict1.update(dict2)
    print dict1
    # 通过列表创建字典
    # 普通方法
    dict3 ={}
    l1 = range(10)
    l2 = list(reversed(l1))
    for i1,i2 in zip(l1,l2):
        dict3[i1] = i2
    print dict3
    #  简单方法
    dict4 = dict(zip(l1,l2))
    print "-------dict4-------"
    print dict4

执行结果

C:\Anaconda2\python.exe D:/lect001/.idea/test001.py
{}
{'a': 1, 'c': [1, 2, 3], 'b': 2}
{'a': 1, 'c': [1, 2, 3], 'b': 2, 'd': 12}
12
{'a': 1, 'c': [1, 2, 3], 'b': 2}
['a', 'c', 'b']
[1, [1, 2, 3], 2]
{'a': 'a', 'c': [1, 2, 3], 'b': 2, '5': 'dfdf', '4': 'aaa'}
{0: 9, 1: 8, 2: 7, 3: 6, 4: 5, 5: 4, 6: 3, 7: 2, 8: 1, 9: 0}
-------dict4-------
{0: 9, 1: 8, 2: 7, 3: 6, 4: 5, 5: 4, 6: 3, 7: 2, 8: 1, 9: 0}

Process finished with exit code 0

集合 set:

# -*- coding: utf-8 -*-

# 集合
if __name__ == '__main__':
    a = set(range(10))
    print a
    b = set(range(5,10))
    print b
    # 并交差异或
    print a | b
    print a & b
    print a - b
    print a ^ b
    # 判断是否为子集合,父集合
    print "-----子集------"
    print a.issubset(b)
    print b.issubset(a)
    print a.issubset(a)
    print "------父集--------"
    print a.issuperset(b)
    print b.issuperset(a)
    print a.issuperset(a)
    

运行结果:

C:\Anaconda2\python.exe D:/lect001/lect001_set.py
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
set([8, 9, 5, 6, 7])
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
set([8, 9, 5, 6, 7])
set([0, 1, 2, 3, 4])
set([0, 1, 2, 3, 4])
-----子集------
False
True
True
------父集--------
True
False
True

Process finished with exit code 0

高级特性

1、列表推导式

# -*- coding: utf-8 -*-

# python 高级特性
if __name__ == '__main__':
    # 列表推导式
    # [ exp for item in collection if condition ]
    a = [x for x in range(10)]
    print a
    b = [2*x for x in range(10)]
    print b
    c = [ 2*x for x in range(10) if x%2==0 ]
    print c
    str_list = ['Welcome','to','python','analysis','course']
    result = [x.upper() for x in str_list if len(x)>3]
    print result

运行结果

C:\Anaconda2\python.exe D:/lect001/lect001_supper_attr.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[0, 4, 8, 12, 16]
['WELCOME', 'PYTHON', 'ANALYSIS', 'COURSE']

Process finished with exit code 0

函数列表(多函数模式,函数式编程)

**python中一切皆对象

**[fun1,fun2]

# -*- coding: utf-8 -*-

# python 函数列表

def remove_space(str):
    """
        remove space
    :param str:
    :return:
    """
    str_no_space = str.replace(' ', '')
    return str_no_space

def remove_dollar(str):
    """
        remove  $
    :param str:
    :return:
    """
    str_no_dollar = str.replace('$', '')
    return str_no_dollar

def clean_str_lst(str_lit, operations):
    result = []
    for item in str_lit:
        for op in operations:
            item = op(item)
        result.append(item)
    return result

if __name__ == '__main__':
    str_list = [' $1.111','$2.222 ','$3.333','$4.dfd df']
    print str_list
    func_list =[remove_space, remove_dollar]
    lst = clean_str_lst(str_list, func_list)
    print lst

运行结果

C:\Anaconda2\python.exe D:/lect001/lect001_fun_list.py
[' $1.111', '$2.222 ', '$3.333', '$4.dfd df']
['1.111', '2.222', '3.333', '4.dfddf']

Process finished with exit code 0

匿名函数 lambda

# 没有函数名
# 单条语句组成
# 语句执行的结果就是返回值
# 可用作sort的key函数
# -*- coding: utf-8 -*-

if __name__ == '__main__':
    str_list = ['Welcome','to','python','analysis','course']
    str_list.sort(key=lambda x: len(x))
    print str_list
    # 按照每个字符串的最末尾的字母排序
    str_list.sort(key= lambda x:x[-1])
    print str_list
C:\Anaconda2\python.exe D:/lect001/lect001_lambda.py
['to', 'python', 'course', 'Welcome', 'analysis']
['course', 'Welcome', 'python', 'to', 'analysis']

Process finished with exit code 0

生成器 generator

构造可迭代对象

每次返回一个值,直到下次调用时,再继续。区别: 函数每次返回一个值

例如 range()  和 xrange

# -*- coding: utf-8 -*-

# 生成器
def gen_test():
    for i in range(10):
        yield i

if __name__ == '__main__':
    gen = gen_test()
    print type(gen)
    print gen
    for i in gen:
        print i

运行结果:

C:\Anaconda2\python.exe D:/lect001/lect001_generator.py
<type 'generator'>
<generator object gen_test at 0x0000000001D54240>
0
1
2
3
4
5
6
7
8
9

Process finished with exit code 0

高阶函数

map, reduce,filter

# -*- coding: utf-8 -*-
import math
# 高阶函数
if __name__ == '__main__':
    """
    函数式编程
        函数可以本身赋给变量。赋值后变量为函数
        准许将函数本身作为参数传入另一个函数
        准许返回一个函数
    """
    print math.sqrt(25)
    fun = math.sqrt
    print fun(9)
    # map(func, list) 将传入的函数func作用到list中的每一个元素上,并将结果组成新的列表返回
    x_2_lst = [x**2 for x in range(10)]
    print x_2_lst
    l = map(math.sqrt, x_2_lst)
    print l
    map1 = map(float, x_2_lst)
    print map1
    # reduce(func(x,y),lst)  其中func必须有两个参数。每次func计算的结果继续和序列的下一个元素做累计计算
    lis = [1,2,3]
    i = reduce(lambda x, y: x - y, lis)
    print i
    reduce1 = reduce(lambda x, y: x * 10 + y, lis)
    print reduce1
    # map 规范字符串
    str_lis = ['liuhaijing','love','chengxiaoxiao']
    s = map(str.title, str_lis)
    print s

    # filter  筛选序列
    # filter(func, list)  , 将func作用于list的每一个元素上,然后根据返回值是True或者false判断保留还是丢弃(true保留,false丢弃)
    print "--------------------filter----------------------------"
    range_list = range(-10, 10)
    print range_list
    filter_list = filter(lambda x: x > 0, range_list)
    print filter_list

运行结果:

C:\Anaconda2\python.exe D:/lect001/.idea/lect001_upper_level_func.py
5.0
3.0
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
[0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0]
-4
123
['Liuhaijing', 'Love', 'Chengxiaoxiao']
--------------------filter----------------------------
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Process finished with exit code 0

 

 

 

 

 

转载于:https://my.oschina.net/captainliu/blog/1596291

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值