为什么我的打印声明重复两次?

时间:2015-05-07 05:48:23

标签: python csv

这是我遇到问题的循环,并且我使用的是我在其他问题中使用的相同CSV文件:

我正在分析有关投诉ID的60MB CSV文件,以及他们对某些公司的投诉。我询问用户他/她想要学习的日期,当他/她输入日期时,我的程序应该生成一行代码,其中包含相应的ID列表。

基本上,input_IDs是ID号列表,input_dates是与每个ID相关的日期列表(月/日/年格式)。

matching_list = []


Date_Input = input("First, input a date in this format, 'Month/Day/Year.' ->       Type in 'Quit' if you are done. : ")

if Date_Input == "Quit":
    print ("Too bad you quit so early!")

for i in range(len(input_dates)):
    if input_dates[i] == Date_Input:
        matching_list.append(input_IDs[i])

if len(matching_list) > 0:
    print ("Here is the list of complaint IDs you can choose from and ask about :", matching_list)

while True:
    new_match_list = []

    if len(matching_list) == 0:
    Date_Input = input ("There are no complaint IDs available for that date! Enter another date: ")

    for x in range(len(input_dates)):
        if input_dates[x] == Date_Input:
           new_match_list.append(input_IDs[x])

    if len(new_match_list)>0:
        print ("Here is the list of complaint IDs you can choose from and ask about :", new_match_list)
        break    

代码正确生成上述ID列表,但产生两个副本,而不是仅仅一个:假设我想要一个发生在上面的ID列表 2015年4月23日,

First, input a date in this format, 'Month/Day/Year.' -> Type in 'Quit' if you are done. : 4/23/2015
Here is the list of complaint IDs you can choose from and ask about : ['1344139', '1344055', '1343332', '1343188', '1343131', '1341190', '1340441', '1338003', '1336832', '1329966', '1301958', '1251144']
Here is the list of complaint IDs you can choose from and ask about : ['1344139', '1344055', '1343332', '1343188', '1343131', '1341190', '1340441', '1338003', '1336832', '1329966', '1301958', '1251144']

为什么要生成两个打印语句,而不仅仅是一个?

1 个答案:

答案 0 :(得分:1)

你有两个打印语句 - 一个在循环之前,一个在结尾。您可以通过删除 while之前的打印块并将其放在循环的开头来解决此问题:

while True:
    if len(new_match_list)>0:
        print ("Here is the list of complaint IDs you can choose from and ask about :", new_match_list)
        break

    new_match_list = []

    if len(matching_list) == 0:
    Date_Input = input ("There are no complaint IDs available for that date! Enter another date: ")

    for x in range(len(input_dates)):
        if input_dates[x] == Date_Input:
           new_match_list.append(input_IDs[x])