如何根据优先级升序排列待办事项列表

Posted

技术标签:

【中文标题】如何根据优先级升序排列待办事项列表【英文标题】:How to ascendingly order a to do list based on priority 【发布时间】:2022-01-21 11:06:56 【问题描述】:

因此,作为实习机会的一部分,我们被告知要制作一个待办事项列表 CLI 应用。问题是我不知道如何按优先级升序对文件中的文本进行排序,任何帮助将不胜感激

这是我的代码:

import typer 
app = typer.Typer()

@app.command()
def help():
    print("""Usage :-
$ ./todo add 2 hello world  # Add a new item with priority 2 and text "hello world" to the list
$ ./todo ls               # Show incomplete priortiy list items sorted by priority in ascending order
$ ./todo del NUMBER       # Delete the incomplete item with the given priority number
$ ./todo done NUMBER      # Mark the incomplete item with given PRIORITY_NUMBER as complete
$ ./todo help             # Show usage
$ ./todo report           # Statistics """)


@app.command()
def add(priority: int,task: str):

    file1=open("ls.txt","r")
    x=len(file1.readlines())
    y=x+1
    file1.close()
    file1=open("ls.txt","a")
    file1.write(str(y)+". "+task + " ["+str(priority)+"]"+ "\n")
    file1.close()


@app.command()
def ls():
    file1=open("ls.txt","r")
    print(file1.read())
   
        
if __name__=="__main__":
    app()
       

这是所需的输出image:

【问题讨论】:

请以文本而非图像的形式提供输出。 【参考方案1】:

我看不到图片,但我猜你想显示按优先级排序的任务:

from pathlib import Path

import typer

app = typer.Typer()
DB_NAME = "ls.txt"


@app.command()
def help():
    HELP_TEXT = """Usage :-
$ ./todo add 2 hello world  # Add a new item with priority 2 and text "hello world" to the list
$ ./todo ls               # Show incomplete priortiy list items sorted by priority in ascending order
$ ./todo del NUMBER       # Delete the incomplete item with the given priority number
$ ./todo done NUMBER      # Mark the incomplete item with given PRIORITY_NUMBER as complete
$ ./todo help             # Show usage
$ ./todo report           # Statistics """
    print(HELP_TEXT)


@app.command()
def add(priority: int, task: str):
    filepath = Path(DB_NAME)
    text = filepath.read_text()
    y = len(text.splitlines()) + 1
    with filepath.open("a") as fp:
        fp.write(f"y. task [priority]\n")


@app.command()
def ls():
    ss = Path(DB_NAME).read_text().splitlines()
    tasks = []
    for line in ss:
        index, tp = line.split(".", 1)
        task, priority = tp.strip("]").rsplit(" [", 1)
        tasks.append((int(priority), int(index), task.strip()))
    for priority, _, task in sorted(tasks):
        print(priority, task)


if __name__ == "__main__":
    app()

【讨论】:

以上是关于如何根据优先级升序排列待办事项列表的主要内容,如果未能解决你的问题,请参考以下文章

SCRUM实践应用

如何根据优先级重新排列列表视图中的项目?

敏捷Scrum开发7大事件之1:产品待办列表优先级排序

Scrum角色划分——绿唤

Scrum的3种角色

Scrum中的产品需求预审