У меня есть код, который читает из файла и должен создавать и распечатывать список районов, а также их количество.

def main():

    #open the file
    myFile = open("Data.txt")

    #read the first line
    firstLine = myFile.readline()

    #initialize a counter
    count = 0

    #for each line in the file
    for dataLine in myFile:

        #strip the end of the line
        dataLine = dataLine.rstrip("\n")

        #split the line into a list
        dataList = dataLine.split(",")

        #create a new list
        districts = []

        #if dataList[3] is not in districts already
        if dataList[3] in districts == False:
            #append dataList[3] to the districts list
            districts.append(dataList[3])
            count = count + 1

    #print the districts list as well as how many were found
    print("Here is a list of all districts:")
    print(" ")
    print(districts)
    print("There are",count,"districts.")
            
    #close the file
    myFile.close

main()

Однако я сталкиваюсь с проблемой, когда кажется, что в список районов из dataList ничего не добавляется. Я уверен, что это связано с тем, как я сформулировал свой код, но я не понимаю, что это может быть. Любая помощь будет принята с благодарностью.

-1
RetroActive 5 Дек 2020 в 18:28

3 ответа

Лучший ответ

if dataList[3] in districts всегда возвращает ложь.

Рассмотрите возможность изменения на

if dataList[3] not in districts:

Кроме того, как указано в комментариях, вы также можете изменить строку на:

dataLine = dataLine.rstrip()
0
Dharman 5 Дек 2020 в 15:39

Команда

    #if dataList[3] is not in districts already
    if dataList[3] in districts == False:

Должно быть

    #if dataList[3] is not in districts already
    if dataList[3] not in districts:

Более того, у вас есть команда

    #create a new list
    districts = []

В вашем цикле for, поэтому вы снова и снова делаете его пустым, не давая ему возможности получить более одного элемента. Переместите его из цикла.

Кстати, почему бы не использовать встроенный модуль csv вместо ручного анализа каждой строки для создания списка ее частей? Вот модифицированная версия вашего кода:

import csv

def main():

    #open the file
    with open("Data.txt") as my_file:
        reader = csv.reader(my_file, delimiter=",")
        
        #ignore the first line
        next(reader)

        #initialize a counter
        count = 0

        #create a new list
        districts = []
        
        #for each line in the file, AUTOMATICALLY CHANGED BY csv.reader() TO A LIST
        for data_list in reader:

            #if data_list[3] is not in districts already
            if data_list[3] not in districts:
                #append data_list[3] to the districts list
                districts.append(data_list[3])
                count += 1

    #print the districts list as well as how many were found
    print("Here is a list of all districts:")
    print()
    print(districts)
    print("There are", count, "districts.")

Заметка:

Вместо имени dataList я использовал имя data_list, чтобы оно соответствовало PEP 8

0
MarianD 5 Дек 2020 в 16:15

Чтобы найти уникальные значения в списке данных, вы можете использовать set

Итак, поскольку данные в столбце 4 - это район, и вы хотите найти уникальные значения этого списка dataList (который является списком всех районов)

unique_districts = list(set(districts)

Здесь set() преобразует районы в уникальные значения, а list() преобразует их обратно в список

def main()
    # get contents of the file into a single list
    with open("Data.txt","r") as fid:
        contents = fid.readlines()

    # assuming the district data is in 4th column
    districts=list(set([line.split(",")[3].rstrip() for line in contents]))
    # length of the districts list is the count

    print("Here are all the districts")
    print(districts)
    print("There are", len(districts), "districts.")
    
0
sudhish 5 Дек 2020 в 16:29