【问题标题】:Appending an item from one list to another将一个列表中的项目附加到另一个列表
【发布时间】:2021-03-17 09:26:57
【问题描述】:

我这里有从文件读取的代码,应该创建和打印一个地区列表,以及有多少地区。

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

【问题讨论】:

  • 注意rstrip("\n")的使用可以替换为strip(),因为它默认会删除换行符

标签: python list for-loop append


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    命令

        #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 代替名称 dataListPEP 8 一致

    【讨论】:

      【解决方案3】:

      if dataList[3] in districts 总是返回 false。

      考虑改成

      if dataList[3] not in districts:
      

      此外,如 cmets 中所述,您可能还希望将行更改为:

      dataLine = dataLine.rstrip()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2018-09-21
        • 2019-03-13
        • 1970-01-01
        • 2021-12-22
        • 2021-08-18
        • 2022-10-25
        相关资源
        最近更新 更多