【问题标题】:How to create two lists from an existing file and compare them to each other?如何从现有文件创建两个列表并将它们相互比较?
【发布时间】:2013-04-13 02:06:34
【问题描述】:

所以我有一个文件,它分为四个不同的类别:Level、Char1、Char2 和 Years 它看起来像这样:(文件继续等)

Level     Char1   Char2   Years

1         Leon    Chris   1990-1999
2         Mario   Luigi   1990-1999
3         Peach   Cloud   1990-1999
4         Leon    Chris   2000-2009
5         Ghost   Garen   2000-2009
6         Mario   Vincent 2000-2009
etc...   etc...   etc..   etc...

我想比较 Char1 和 Char2 并打印出现在 1990-1999 年但不在 2000-2009 年出现的名称,因此它会打印

These names are going away:
Luigi Peach Cloud etc...

我认为您需要将它们放入列表或字典文件中,但我不知道如何将 char1 和 char2 分开并将它们与年份进行比较。对此的任何帮助都将非常有帮助!

【问题讨论】:

  • 使用str.split() 分隔列:"1 Leon Chris 1990-1999".split()-->['1', 'Leon', 'Chris', '1990-1999'] `
  • 它们是制表符分隔的吗?
  • 它们不是制表符分隔的,它在文件中显示为:1,Leon,Chris,1990-1999
  • @user2276168 所以是逗号分隔的?
  • @F3AR3DLEGEND 假设是这样

标签: python list python-3.x dictionary


【解决方案1】:
>>> import csv
>>> with open('test.csv') as f:
        print f.read()


Level,Char1,Char2,Years
1,Leon,Chris,1990-1999
2,Mario,Luigi,1990-1999
3,Peach,Cloud,1990-1999
4,Leon,Chris,2000-2009
5,Ghost,Garen,2000-2009
6,Mario,Vincent,2000-2009
>>> with open('test.csv') as f:
        r = csv.reader(f)
        next(r, None) # skip header

        names = set()
        for level, char1, char2, years in r:
            if years == "1990-1999":
                names += {char1, char2}
            else: # 2000 - 2009
                names -= {char1, char2}
        print "These names are going away"
        print " ".join(names)


These names are going away
Peach Luigi Cloud

【讨论】:

    【解决方案2】:

    这种“哪些名字在这个组而不在这个组”是 “集合”的工作。然后 Python 在内部实现了 - 因此,您只需按日期列对数据进行分组,然后使用 设置“减法” - 与 “该集合中不包含在该集合中的元素 其他集合”以获得您的结果。

    假设您只有两个已编码的数据组,这就是您所需要的:

    from collections import defaultdict
    
    data = defaultdict(set)
    
    with open("myfilename") as file_:
       for line in file_:
          line = line.split()
          if len(line) == 4 and line[0].isdigit():
              data[line[3]].add(line[1])
              data[line[3]].add(line[2])
       print ("These characters are going away:")
       print (" ".join(data["1990-1999"] - data["2000-2009"]))
    

    “defaultdict”是一个 Python 的精妙之处,在这种情况下只需为我们节省 2 行代码 在 for 循环中 - 没有它,必须添加:

    if line[3] not in data:
        data[line[3]] = set()
    

    到上面的代码。

    【讨论】:

      【解决方案3】:

      我发现对此类文件的一个有用模式是将数据读入一个字典,该字典以第一行的标题项为索引。使用这种方法,解决方案(从stdin 读取逗号分隔的数据文件)如下所示:

      import sys
      
      data = {}
      hdrLabel = sys.stdin.readline().rstrip().split(",")
      for header in hdrLabel:
          data[header] = []
      
      for line in sys.stdin:
          for (i,item) in enumerate(line.rstrip().split(",")):
              data[hdrLabel[i]].append(item)
      
      def getCharSet(cols,yrRange):
          s = set()
          for c in cols:
              s = s | {data[c][i] for i in range(len(data[c])) 
                  if data["Years"][i] == yrRange}
          return s
      
      set19 = getCharSet(["Char1","Char2"],"1990-1999")
      set20 = getCharSet(["Char1","Char2"],"2000-2009")
      print (set19-set20)
      

      这种方法的优点是它允许在读入数据后进行许多不同的数据操作,而不必担心列号是否正确等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-08
        • 1970-01-01
        • 1970-01-01
        • 2019-01-03
        • 2012-06-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多