0

所以我有一个文件,它分为四个不同的类别: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 分开并将它们与年份进行比较。对此的任何帮助都将非常有帮助!

4

3 回答 3

0

这种“哪些名字在这个组而不在这个组”是“集合”的工作。然后 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 的精妙之处,在这种情况下,只需在 for 循环中为我们节省 2 行代码 - 没有它,就必须添加:

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

到上面的代码。

于 2013-04-13T02:42:35.893 回答
0
>>> 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
于 2013-04-13T02:48:13.143 回答
0

我发现像这样的文件的一个有用模式是将数据读入一个字典,该字典以第一行的标题项为索引。使用这种方法,解决方案(从 读取逗号分隔的数据文件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)

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

于 2013-04-13T03:02:13.837 回答