提问人:user22897049 提问时间:11/11/2023 最后编辑:petezurichuser22897049 更新时间:11/11/2023 访问量:62
如何按升序对 txt 文件的项目价格进行排序?
How do i sort the prices of items of a txt file in ascending order?
问:
我想使 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)
但它没有工作,它没有分类,而是保持不变。你们中有人知道如何解决它吗?
答:
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
评论
{}
products
format_products()