如何按升序对 txt 文件的项目价格进行排序?

How do i sort the prices of items of a txt file in ascending order?

提问人:user22897049 提问时间:11/11/2023 最后编辑:petezurichuser22897049 更新时间:11/11/2023 访问量:62

问:

我想使 TXT 文件中的产品价格在显示中按升序显示。 我的 txt 文件是这样的:

R001,Angel Eyes,Romantic,2.0,Available
R002,Hearts on Fire,Romantic,158.0,Available
R003,Purple Rush,Romantic,288.0,Available
B001,Sweet Nothings,Birthday,98.0,Available
B002,Summer Surprise, Birthday,158.0,Available
GO001,Savannah,Grand Opening,158.0,Available
GO002,The Tropics,Grand Opening,168.0,Available
C001,Tranquility,Condolence,151.0,Available
C002,Memories,Condolence,151.0,Available
A001,Garden of Hearts,Anniversary,200.0,Available
A002,Treasured Blooms,Anniversary,188.0,Available
A003,Ray of Light,Anniversary,288.0,Available

我已经为它创建了一个格式函数。物品必须从顶部,最低价格到最低价格,最高价格排序。

所以我试着为它编写一个排序代码,如下所示:

def sort_price(products, addons):
  #sorting the price in ascending order
      infile = open("products.txt")
      sorted_products = sorted(products.items(),key=lambda item: item[1][2])
      print(sorted_products)
     format_products(products)

但它没有工作,它没有分类,而是保持不变。你们中有人知道如何解决它吗?

Python 项目

评论

1赞 Klaus D. 11/11/2023
请为您的代码和数据使用代码格式化(按钮){}
1赞 buran 11/11/2023
请发布最小的可重复示例。什么是,什么是?productsformat_products()
0赞 Matthias 11/11/2023
为什么你要打开一个你从未使用过的文件?
0赞 user22897049 11/11/2023
format_products() 是我制作的另一个函数,用于根据 Itemcode、花名、类别、价格、状态以适当的间距格式化显示中的 txt 文件数据。
0赞 user22897049 11/11/2023
为了回答 matthias,这是一个我必须经常打开的文件,以使其在显示屏中列出,供假想的客户从中订购,因为我编写了一个销售管理和库存管理菜单和子菜单程序,用户可以在其中更新或添加产品以及订购产品。每次下达订单时,订单也需要出现在新的 txtfile 中。

答:

1赞 Sash Sinha 11/11/2023 #1

请考虑创建一个帮助程序函数,以便在排序之前将文件分析为产品列表:

import dataclasses
import pathlib


@dataclasses.dataclass
class Product:
  code: str
  name: str
  category: str
  price: float
  status: str


def parse_products(file_path: pathlib.Path) -> list[Product]:
  """Parses products from a file into a list of Product objects.

  The file should contain product data in the format:
  'Code,Name,Category,Price,Status' (without quotes), each on a new line.
  
  Args:
    file_path: A Path object representing the path to the csv file 
               containing product data.
  """
  with file_path.open('r') as file:
    products = []
    for line in file.readlines():
      code, name, category, price, status = line.strip().split(',')
      products.append(Product(code, name, category, float(price), status))
    return products


def main() -> None:
  products = parse_products(pathlib.Path('products.txt'))
  for p in sorted(products, key=lambda product: product.price):
    print(f'{p.code},{p.name},{p.category},{p.price},{p.status}')
    # print(','.join([str(getattr(p, attr)) for attr in p.__dataclass_fields__]))


if __name__ == '__main__':
  main()

输出:

R001,Angel Eyes,Romantic,2.0,Available
B001,Sweet Nothings,Birthday,98.0,Available
C001,Tranquility,Condolence,151.0,Available
C002,Memories,Condolence,151.0,Available
R002,Hearts on Fire,Romantic,158.0,Available
B002,Summer Surprise, Birthday,158.0,Available
GO001,Savannah,Grand Opening,158.0,Available
GO002,The Tropics,Grand Opening,168.0,Available
A002,Treasured Blooms,Anniversary,188.0,Available
A001,Garden of Hearts,Anniversary,200.0,Available
R003,Purple Rush,Romantic,288.0,Available
A003,Ray of Light,Anniversary,288.0,Available