使用 for 函数进行迭代时如何停止追加到列表并开始另一个列表?

问题描述 投票:0回答:1

我正在尝试添加更多用户来回答一些问题。但保存答案的新文件将答案显示在一行中。因此,用户及其答案与各自的标题不匹配。在本例中,我输入了 3 个用户并回答了 3 个问题;并在使用 Pandas 创建表时收到这些错误消息。

pandas.errors.ParserError:标记数据时出错。 C 错误:第 5 行应有 3 个字段,但看到了 9

我尝试使用元组,但没有任何效果。谢谢。

def example():
"""Get answers from the new users and save them in file answers.csv"""
#`Open file named filename_answers in append mode a+
   filename_answers = answers.csv
   fanswers_new_users = open(filename_answers, "a+")
   writer_answers_new = csv.writer(fanswers_new_users)
   questions_add_user = str(input("Do you wish to add another user?Enter Yes/No to continue"))
   q_ = questions_add_user.title()
   print("These are new user answers:\n")
   while q_ == "Yes":
    #headers_questions_enumerate is a list holding all enumerated questions
      for preguntas in headers_questions_enumerate[:]:
         print(preguntas)
         preguntar_1 = str(input("Please, Answer the question:\n"))
         preguntar_ = preguntar_1.title()
         respuestas_new_user.append(preguntar_)
      questions_add_user = str(input("Do you wish to add user?Enter Yes/No to continue \n"))      
      q_ = questions_add_user.title()   
      if q_! = "Yes":
      for rep in respuestas_new_user:
         respuestas_new_user_save.append(rep)
      values_dictionary.append(respuestas_new_user_save)
      for separados in values_dictionary:
         pegar_defintivo.append(separados)
      writer_answers_new.writerows(pegar_defintivo)
      fanswers_new_users.close()
      break   
pandas for-loop iteration cvs
1个回答
0
投票

您应该为每个用户重置您的

respuestas_new_user_save
列表。

import csv

def example():
    """Get answers from the new users and save them in the file answers.csv"""
    filename_answers = 'answers.csv'  # Make sure to enclose the filename in quotes
    fanswers_new_users = open(filename_answers, "a+")
    writer_answers_new = csv.writer(fanswers_new_users)
    questions_add_user = str(input("Do you wish to add another user? Enter Yes/No to continue"))
    q_ = questions_add_user.title()
    print("These are new user answers:\n")
    
    while q_ == "Yes":
        respuestas_new_user_save = []  # Reset the list for each user
        for preguntas in headers_questions_enumerate[:]:
            print(preguntas)
            preguntar_1 = str(input("Please, Answer the question:\n"))
            preguntar_ = preguntar_1.title()
            respuestas_new_user_save.append(preguntar_)
        
        questions_add_user = str(input("Do you wish to add user? Enter Yes/No to continue\n"))
        q_ = questions_add_user.title()
        
        if q_ != "Yes":
            writer_answers_new.writerow(respuestas_new_user_save)  # Write the user's answers to a new row
            fanswers_new_users.close()
            break

example()
© www.soinside.com 2019 - 2024. All rights reserved.