Python3内置函数(21-30)

# 21. bin()
# 返回一个整数 int 或者长整数 long int 的二进制表示。
num1 = bin(10)
print(num1)

# 22. file()
# file() 函数用于创建一个 file 对象,它有一个别名叫 open()
# f1=file('慎独','r',encoding='utf8')
f1 = open('慎独', 'r', encoding='utf8')
print(f1.read())

# 23. iter()
# 来生成迭代器。
lst = [1, 2, 6, 5, 8]
for i in iter(lst):
    print(i)


# 24. property()
# 在新式类中返回属性值
# class property([fget[, fset[, fdel[, doc]]]])
# fget -- 获取属性值的函数
# fset -- 设置属性值的函数
# fdel -- 删除属性值函数
# doc -- 属性描述信息
class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")


# 25. tuple()
# 将列表转换为元组。
a = [1, 2, 3, 4, 56, 676]
print(tuple(a))

# 26. bool()
# 将给定参数转换为布尔类型,如果没有参数,返回 False
# bool 是 int 的子类。
print(bool(12))


# 27. filter()
# 用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
# Pyhton2.7 返回列表,Python3.x 返回迭代器对象
# filter(function, iterable)
# function -- 判断函数。
# iterable -- 可迭代对象。


# 函数
def is_odd(n):
    return n % 2 == 1


# 可迭代对象
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

newlist = filter(is_odd, lst)
newlist = list(newlist)  # 有些地方没有这句就打印不出来列表,而打印函数地址
print(newlist)

# 28. len()
# 返回对象(字符、列表、元组等)长度或项目个数
str2 = 'jhafdkjhasjdfkh'
print(len(str2))

# 29. range()
# 创建一个整数列表,一般用在 for 循环中
# range(start, stop[, step])
# start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
# stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
# step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

for i in range(1, 11, 2):
    print('', i, end='')
print()

# 30. type()
# 只有第一个参数则返回对象的类型
# type(object)

# 三个参数返回新的类型对象
# type(name, bases, dict)
# name -- 类的名称。
# bases -- 基类的元组。
# dict -- 字典,类内定义的命名空间变量。

num3 = 23
print(type(num3))


class X(object):
    a = 1


print('X', (object,), dict(a=1))

要点:

  •  bin() 求二进制
  • file()  就是open()函数 Python3已经废除
  • iter() 用来生成迭代器
  • property() 在新式类中返回属性值
  • tuple() 将列表转换为元组
  • bool() 将给定值转换为布尔值
  • filter() 过滤掉不符合判断函数规则的,返回符合条件的
  • len() 求字符,列表,元组的长度或项目个数
  • range() 创建一个列表注意: range(a,b,c) c为步长的用法
  • type() 一个参数:返回对象类型,三个参数:返回新的类型对象

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章