鱼C论坛

 找回密码
 立即注册
查看: 890|回复: 6

[已解决]python行排序问题

[复制链接]
发表于 2020-6-7 21:03:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
文本文件 input.txt 中数据存储形式是

2 乘以 8

3 乘以 8

5 乘以 5

请编写程序从该文件中读取数据,计算每行乘积,并按结果降序排名,输出到文件 output.txt 中,如果结果一样,则排名顺序与原始顺序一致。

output.txt 文件中的数据格式为:

5 乘以 5 25

3 乘以 8 24

2 乘以 8 16



求助各位大佬帮忙解答 感谢
最佳答案
2020-6-7 21:22:16
如果编码报错,把两个open的 encoding = 'utf-8'  去掉

  1. with open('input.txt',encoding='utf-8') as f:
  2.     temp = []
  3.     count = 0
  4.     for i in f:
  5.         if i != '\n':
  6.             i = i.split('\n')[0]
  7.             temp.append([int(i) for i in i.split()[0::2]])
  8.             temp[count] += [temp[count][0]*temp[count][1]]
  9.             count += 1
  10.     temp = sorted(temp,key=lambda x:x[2])
  11. with open('output.txt','w',encoding='utf-8') as f:
  12.     for i in temp[::-1]:
  13.         f.write(f'{i[0]} 乘以 {i[1]} {i[2]}\n')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-6-7 21:22:16 | 显示全部楼层    本楼为最佳答案   
如果编码报错,把两个open的 encoding = 'utf-8'  去掉

  1. with open('input.txt',encoding='utf-8') as f:
  2.     temp = []
  3.     count = 0
  4.     for i in f:
  5.         if i != '\n':
  6.             i = i.split('\n')[0]
  7.             temp.append([int(i) for i in i.split()[0::2]])
  8.             temp[count] += [temp[count][0]*temp[count][1]]
  9.             count += 1
  10.     temp = sorted(temp,key=lambda x:x[2])
  11. with open('output.txt','w',encoding='utf-8') as f:
  12.     for i in temp[::-1]:
  13.         f.write(f'{i[0]} 乘以 {i[1]} {i[2]}\n')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-7 21:34:13 | 显示全部楼层
  1. def WriteOutPut():

  2.     import re
  3.     with open("input.txt", "r", encoding="utf-8") as f:
  4.         text = re.findall("(\d+).*?(\d+)", f.read())

  5.     with open("output.txt", "w", encoding="utf-8") as f:
  6.         for one,two in text:
  7.             txt = f"{one} 乘以 {two} 等于 {int(one)*int(two)}\n\n"
  8.             f.write(txt)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-7 21:35:28 | 显示全部楼层
Twilight6 发表于 2020-6-7 21:22
如果编码报错,把两个open的 encoding = 'utf-8'  去掉

你怎么这么快,没天理呀:10_274:}:10_274:}
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-7 21:36:33 | 显示全部楼层
Stubborn 发表于 2020-6-7 21:35
你怎么这么快,没天理呀:10_274:}:10_274:}


正则还可以这样用 学到了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-7 21:42:44 | 显示全部楼层
Twilight6 发表于 2020-6-7 21:36
正则还可以这样用 学到了

大佬,加个V呀
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-7 21:43:46 | 显示全部楼层

被大佬说大佬真恐怖
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-21 12:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表