将 \n 添加到列表列表中的最后一个元素

Add \n to the last element of a list, in a list of lists

提问人:tekkyprograms 提问时间:2/10/2023 最后编辑:tekkyprograms 更新时间:2/10/2023 访问量:119

问:

所以我有一个外部文件,其中每行都有一个任务格式如下:

用户、任务标题、任务描述、分配日期、截止日期、已完成(是/否)

我创建了一个列表列表,其中主列表中是上面一行的列表,基本上每个元素都与“,”分开。

所以它看起来像这样:

[['User', 'Title of task', 'Description of task', 'Date assigned', 'Due Date', 'Completed (Yes/No)']]

我正在尝试更改最后一个列表的最后一个元素,以在末尾包含“\n”。

这是我实现的代码:

with open('tasks.txt', 'w') as f2:  
    count = 0         
    for i in list_of_tasks:
        count += 1
        if count == len(list_of_tasks):
            list_of_tasks[i][-1] = str(f"{list_of_tasks[i][-1]}\n")
            f2.write(", ".join(i))
        else:
            f2.write(", ".join(i))

这是我收到的错误:

list_of_tasks[i][-1] = str(f"{list_of_tasks[i][-1]}\n")
                                  ~~~~~~~~~~~~~^^^
TypeError: list indices must be integers or slices, not list

最终,我试图实现的是编辑此外部文件中每行的部分内容。我遇到的最初问题是写入文件后的间距被弄乱了,因此我试图弄清楚如何将\n添加到此列表列表中最终列表中的最后一个元素。

如果有帮助,以下是完整的功能:

def view_mine(username):
    # opens tasks.txt as read only and assigns it as a variable named f1

    with open('tasks.txt', 'r') as f1:
            
            
            x = 1
            list_of_tasks= []
            other_tasks = []
            for line in f1:
                line3_split = line.split(', ')
                
                if line3_split[0] == username:
                    user_format = f"""
                    Task {x}:          {line3_split[1]}
                    Assigned to:       {line3_split[0]}
                    Date assigned:     {line3_split[3]}
                    Due date:          {line3_split[4]}
                    Task complete?     {line3_split[5]}
                    Task description:  
                    {line3_split[2]}
                    """
                    print(user_format)
                    x += 1
                
                    list_of_tasks.append(line3_split)
                else:
                    other_tasks.append(line3_split)
                
            selection = int(input(f"Which task do you want to select (1-{x-1}) or enter '-1' to return to main menu? ")) -1
            if selection == -2:
                return

            else:
            
                mark_or_edit = int(input(f"To mark as complete enter '1'. To edit the task enter '2'."))

                if mark_or_edit == 1:
                
                    if list_of_tasks[selection][-1] == "No":
                        list_of_tasks[selection][-1] = "Yes\n"
                    elif list_of_tasks[selection][-1] == "No\n":
                        list_of_tasks[selection][-1] = "Yes\n"
                

                elif mark_or_edit == 2:
                    user_or_date = int(input("To edit user assigned enter '1'. To edit due date enter '2'. "))
                    if user_or_date == 1:
                        user_check = input("Which user do you want to assign this task to? ")
                        existing_names_list = []
                        with open('user.txt', 'r') as f:

                            for line in f:
                                existing_names = line.split(', ')
                                existing_names_list.append(existing_names[0])
                            if user_check in existing_names_list:
                                list_of_tasks[selection][0] = user_check
                            else:
                                print("User does not exist.")
                    elif user_or_date == 2:
                        new_date = input("Enter the new due date (XX XXX XXXX): ")
                        list_of_tasks[selection][4] = new_date
            
            
                with open('tasks.txt', 'w') as f2:  
                        count = 0         
                        for I in list_of_tasks:
                            count += 1
                            if count == len(list_of_tasks):
                                list_of_tasks[i][-1] = str(f"{list_of_tasks[i][-1]}\n")
                                f2.write(", ".join(i))
                            else:
                                f2.write(", ".join(i))
                        
                        for i in other_tasks:
                            f2.write(", ".join(i))

            
    return
python list typeerror 元素 fwrite

评论

0赞 tekkyprograms 2/10/2023
我仍然收到同样的错误。
0赞 Kelly Bundy 2/10/2023
最好展示一个好例子.list_of_tasks
0赞 JonSG 2/10/2023
你在找吗?list_of_tasks = [", ".join(task) + "\n" for task in list_of_tasks]

答:

0赞 Xhulio Xhelilai 2/10/2023 #1

问题出在:

for i in list_of_tasks

在这种情况下,i 是一个字符串,您正在尝试将其用作列表中的索引。

我不确定您到底要完成什么,但我认为您的代码在逻辑上有一些不准确之处。我希望以下代码能够完成工作:

with open('tasks.txt', 'w') as f2:  
count = 0        
for sub_list in list_of_tasks: 

    for i in range(len(sub_list)):

        if i == len(sub_list) - 1:
            temp = sub_list[i] + '\n'
            f2.write(temp)
        else:
            f2.write(sub_list[i] + ', ')

您提供的列表的上述代码的输出为:

User, Title of task, Description of task, Date assigned, Due Date, Completed (Yes/No)

末尾包含“\n”,即使它不明显。

似乎你有一个列表列表,所以是一个 2D 数组,其中每个元素都是一个字符串。因此,您必须对第一个维度(每个列表如此)循环一次,然后对第二个维度(对于列表中的每个字符串)循环一次。每次都有每个字符串,你就可以创建你要尝试的句子。

评论

0赞 tekkyprograms 2/10/2023
然后我收到这个错误: f2.write(“, ”.join(i)) ^^^^^^^^^^^^ TypeError:只能加入一个可迭代对象
0赞 Xhulio Xhelilai 2/10/2023
在这种情况下,i 是一个索引,而不是一个字符串,因此 .join 将不起作用。您必须使用 list_of_tasks[i]。但是您的代码也存在一些逻辑错误。给我一些时间。
0赞 Xhulio Xhelilai 2/10/2023
@tekkyprograms 告诉我上面的帖子是否对您有所帮助,如果对您有帮助,请不要忘记投票是正确和有用的。此外,最好更改帖子的标题,包括您收到的错误。
0赞 tekkyprograms 2/10/2023
它关闭了!所以我不再收到错误,但是这是将\n添加到所有子列表的最后一个元素,而不仅仅是最后一个子列表。例如:[[a, b, c, d\n\n], [e, f, g, h\n\n], [I, j, k, l\n]] 本质上是它给我的。我希望结果为 [[a, b, c, d\n], [e, f, g, h\n], [I, j, k, l\n]]