美文网首页
Python练习2

Python练习2

作者: 大红中 | 来源:发表于2017-10-30 21:16 被阅读0次
  1. 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
def int2str(num):
    return str(num)


def str2int(string):
    return int(string)


num_list = [45, 2, 34, 65, 653, 2435, 1, 4, 234]
num_list.sort()
print num_list
num_str = ' '.join(map(int2str, num_list))
with open('num_list.txt', 'wb') as f:
    f.write(num_str)

with open('num_list.txt', 'rb') as f:
    new_list = map(str2int, f.read().split())

new_list.reverse()
print new_list
new_str = ' '.join(map(int2str, new_list))

with open('num_list.txt', 'ab') as f:
    f.write('\n' + new_str)
执行结果1
  1. 分别把 string, list, tuple, dict写入到文件中
f_str = 'hello'
f_list = ['alex', 'hello', 'javier']
f_tup = ('hi', 'python',)
f_dict = {'name': 'javier', 'age': 18}

with open('text2.txt', 'wb') as f:
    f.write('string:{string}\nlist:{list}\ntuple:{tuple}\ndict:{dict}\n'.format(string=f_str, list=str(f_list), tuple=str(f_tup), dict=str(f_dict)))
执行结果2

相关文章

  • 笨办法学C 练习2:用Make来代替Python

    练习2:用Make来代替Python 原文:Exercise 2: Make Is Your Python Now...

  • Python练习2

    把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中 分...

  • Python练习2

    Python练习----通过匹配提取符合要求的DataFrame的子集 import pandas as pd i...

  • python练习(2)

    python学习的第二周,这周学习继续学习python基础,主要是生成器、函数式编程、模块。部分练习如下: 下周将...

  • python练习2

    1、编写一个程序,查找所有此类数字,它们可以被7整除,但不能是5的倍数(在2000和3200之间(均包括在内))。...

  • Python-100 练习题 02

    练习题2 的网址: http://www.runoob.com/python/python-exercise-ex...

  • 2019-01-20 数据蛙第二周学习总结 Python入门 B

    本周完成:课程中视频及《Python从入门到实践》2-6章,Python练习完成5道。 练习题进度不足,MySQL...

  • 菜鸟编程学习(python‘++’--016)

    Python 练习实例25 Python 100例 题目:求1+2!+3!+...+20!的和。 程序分析:此程序...

  • python编程练习2

    题目:明明的随机数原题目的表述有点复杂,我理解下来就是有一组随机数,对其去重之后按升序排序,自己写了下面的代码,进...

  • [python]练习笔记2

    filter和列表生成器的区别1.列表生成器接受的是序列,string、tuple、range、set、list、...

网友评论

      本文标题:Python练习2

      本文链接:https://www.haomeiwen.com/subject/neimpxtx.html