• python语法积累(持续更新)


    1、round
    round(x,n)方法返回 x 的小数点四舍五入到n个数字
     
    2、random实现随机选择不重复的元素
    利用Python中的randomw.sample()函数实现
    resultList=random.sample(range(x,y); # sample(x,y)函数的作用是从序列x中,随机选择y个不重复的元素。
     
    3、%d 是整形通配符,%s是字符串通配符
    print "一周有%d分钟" %minites
    print "一周有%s秒"%str(seconds)
     
    4、TypeError: 'module' object is not callable
    原因分析:
    Python导入模块的方法有两种:import module 和 from module import,区别是前者所有导入的东西使用时需加上模块名的限定,而后者不要。
    正确的代码:
    >>> import Person
    >>> person = Person.Person('dnawo','man')
    >>> print person.Name
    >>> from Person import *
    >>> person = Person('dnawo','man')
    >>> print person.Name
     
    5、使用map将list中的str转化成int
    语法
    map() 函数语法:
    map(function, iterable, ...)
    参数
    ● function -- 函数,有两个参数
    ● iterable -- 一个或多个序列
    示例
    map(str,[1,2,3.2,4,5])
    #将list中的str转换成int、float
    data = ['1','3.2','2']
    data = map(eval, data)
    print data
     
    #将list中的intfloat转换成str
    #方法一
    array=[1,2,3.2,4,5]
    new_array=map(str,array)
    print new_array
    #方法二
    array1=[1,2,3,4,5]
    new_array1=[str(x) for x in array1]
    print new_array1
     
    6、使用x for x in 表达式
    #获取1301到1500中间的200个数字,并用","隔开
    a=[index for index in range(1301,1501)]
    str= str(a)
    print str.replace("[","").replace("]","").replace(", ",",")
     
    7、reduce用作累计运算
    reduce(...)
    reduce(function, sequence[, initial]) -> value
    示例
    def multiply(a,b):
    return a*b
    print reduce(multiply,(1,2,3,4))
     
    8、filter 用作过滤序列
    filter(...)
    filter(function or None, sequence) -> list, tuple, or string
    示例
    #方法一
    def is_odd(x):
    return x%2==1
    print filter(is_odd,(1,2,3,4,5,6))
    #方法二
    print filter((lambda x:x%2==1),(1,2,3,4,5,6))
     
    9、sorted 用作排序,reverse=False正序,reverse=True逆序排列
    sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
    示例
    print sorted(["zara","asb","hm"],reverse=True)
     
    #将嵌套列表排序
    L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
    new_dict=dict(L)
    b=sorted(new_dict.items(),key=lambda x: x[0],reverse=False) #按姓名正序排列
    c=sorted(new_dict.items(),key=lambda x: x[1],reverse=True) #按数字逆序排列
     
     
  • 相关阅读:
    POJ 1166 The Clocks 高斯消元 + exgcd(纯属瞎搞)
    防止登录页面出如今frame中
    android--显式跳转和隐式跳转的差别使用方法
    卫星照片
    poj 2586 Y2K Accounting Bug (贪心)
    【转】关于Python脚本开头两行的:#!/usr/bin/python和# -*- coding: utf-8 -*-的作用 – 指定文件编码类型
    【转】在Eclipse中使用PyDev进行Python开发
    【转】eclipse + Pydev 配置Python开发环境
    【转】Python自动化测试 (一) Eclipse+Pydev 搭建开发环境
    【转】Eclipse的启动问题【an error has occurred see the log file】
  • 原文地址:https://www.cnblogs.com/echoqi/p/8099108.html
Copyright © 2020-2023  润新知