将一个列表中的项目附加到另一个列表

Appending an item from one list to another

我这里有代码,它从一个文件中读取并应该创建和打印一个选区列表,以及其中的数量。

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 添加到地区列表中。我确定这与我对代码的措辞方式有关,但我不清楚它可能是什么。任何帮助将不胜感激。

命令

    #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.")

注:

我使用 data_list 而不是名称 dataList 以与 PEP 8

保持一致

if dataList[3] in districts 总是 returns 错误。

考虑将其更改为

if dataList[3] not in districts:

此外,如评论中所述,您可能还想将该行更改为:

dataLine = dataLine.rstrip()

要在数据列表中查找唯一值,您可以使用 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.")