小记 用python进行排序

简介: Linux 中可以使用 sort 进行排序,python中也一样,那么怎样实现把一个数字的 list 从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,再追加到文件的下一行中呢?思路如下:1、取一个列表内容2、对列表内容使用 sort 进行排序,并打...

Linux 中可以使用 sort 进行排序,python中也一样,那么怎样实现把一个数字的 list 从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,再追加到文件的下一行中呢?


思路如下:

1、取一个列表内容

2、对列表内容使用 sort 进行排序,并打印出结果

3、打开一个文件,将正序排列后的 list 内容写入文件中,添加换行符

4、再次将列表内容进行反序排列,并打印出来

5、将反序排列后的内容追加到前一个文件中


# -*- coding:utf-8 -*-
#@Time      :2017/10/30 23:29
#@Author    :zhouyuyao
#@File      :sort.py

import codecs
list = ['2','4','3','9','1','7']
list.sort()       # 对 list 进行排序
print(list)       # 打印正序排列的 list
f=codecs.open('sort.txt','w')    # w 表示写
f.writelines(str(list)+'\n')     # 将正序排列的 list 写入 sort.txt 文件,并添加换行符
list.sort(reverse=True)    # 将 list 反序排列
print(list)
f=codecs.open('sort.txt','a')    # a 是追加,将反序排列的了 list 结果追加到文件中
f.write(str(list))


目录
相关文章
|
3月前
|
Python
排列python
排列python
15 0
|
12天前
|
存储 安全 数据处理
python如何将数据写到数组里
【4月更文挑战第12天】
|
1月前
|
Python
Python系列(22)—— 排序函数
Python系列(22)—— 排序函数
|
1月前
|
存储 搜索推荐 索引
Python中的列表怎么排序
Python中的列表怎么排序
16 0
|
1月前
|
Python
Python生成列表进行排序
Python生成列表进行排序
14 0
|
1月前
|
Python
Python列表排序
Python列表排序
16 0
|
2月前
|
搜索推荐 Python
写个python排序代码
写个python排序代码
36 7
|
3月前
|
数据采集 机器学习/深度学习 算法
Python小姿势 - # Python的字典排序
Python小姿势 - # Python的字典排序
|
8月前
|
存储 索引 Python
python中的数组详解
python中的数组详解
117 1
|
搜索推荐 算法 索引
python--排序总结
python--排序算法总结
90 0
python--排序总结