day11

2018-10-12  本文已影响0人  13147abc

模块的使用

 import test1

# # 使用test1中的整型变量test_a
 print(test1.test_a + 100)

 # 使用test1中的函数test1_func1
 test1.test1_func1()

 from test1 import test_a, test1_func1
 from test1 import *
 print('当前模块:', test_a)
 print(test1_func1())

 print(name)
 import test1 as TS

 print(TS.name)

 from test1 import name as test1_name, test1_func1 as other_func, test_a
 print(name)  # 使用当前模块的name变量
 print(test1_name)  # 使用test1中的name
 other_func()
 print(test_a)
import test1
# import test1
from test1 import test_a as AA
print(test1.test_a, AA)

选择性导入(阻止导入)

# import random
import math

# import random
# (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

import color

(255, 255, 255)
color.white
color.white
color.red
color.randow_color()

迭代器

iter1 = iter('abcd')
print(iter1)

print(next(iter1))
print(next(iter1))

for x in range(5):
    print(x)

print(next(iter1))
print(next(iter1))
# print(next(iter1))  # StopIteration
iter1 = iter(['abc', 10, 'name'])
print('=====')
for x in iter1:
    print(x)

print('====')

# print(next(iter1))

生成式和生成器

# 产生一个生成器,生成器中可以生成的数据是数字0~4(每个元素是数字)
ge1 = (x for x in range(5))
print(ge1)#<generator object <genexpr> at 0x000001770E1FA780>

print(next(ge1))#0
print(next(ge1))#1

print('=========')
for item in ge1:
    print(item)# 2 、3 、 4

ge2 = (x*2 for x in range(5))
print('=========')
for item in ge2:
    print(item)#0、2 、4、6、8


ge2 = ([x, x*2] for x in 'abc')
print(next(ge2))#['a', 'aa']

print('===========')
ge2 = (x for x in range(5) if x%2)

for item in ge2:
    print(item)#1 3
def func1(n):
    print('你好,生成器!!')
    for x in range(n+1):
        print(x)
        yield x
        print('yeye')

ge3 = func1(3)
print(ge3)

print('=:',next(ge3))  #    0
print('=:',next(ge3))  # 1
print(next(ge3))  #  2
print(next(ge3))  # 3
# print(next(ge3))

def func2():
    str1 = 'abcdef'
    index = 0
    while index < len(str1):
        yield str1[index]
        index += 1

ge4 = func2()

print(next(ge4))
#
print(next(ge4))
print(list(ge4))

def func3():
    num = 0
    while True:
        yield num
        num += 1

ge5 = func3()
print(ge5)
print('==:',next(ge5))
print('==:',next(ge5))

print('========')
for _ in range(5, 100):
    print(next(ge5))

print('=======')
print(next(ge5))

# 生成器生成的数据的规律:奇数就返回他本身,偶数就返回它的2倍

def func2(n):
    for x in range(n):
        yield x, 2*x, 3*x
        # yield 2*x
        # yield 3*x
        # if x%2:
        #     yield x
        # else:
        #     yield x*2

g6 = func2(5)
print(next(g6))
print(next(g6))
print(next(g6))

文件的读和写

========================文件的读操作=====================

#1.打开文件

f1 = open('./test1.txt', 'r', encoding='utf-8')

#2.读文件中内容

content = f1.read()
print(type(content), content)

# 3.关闭文件

f1.close()

==================文件的写操作==================

#1.打开文件

f2 = open('./test1.txt', 'w', encoding='utf-8')

# 2.写入文件

# f2.write(content+'hello world')
f2.writelines(['abc\n', '123\n', 'aaaaa\n'])
上一篇 下一篇

猜你喜欢

热点阅读