簡體   English   中英

如何從現有文件創建兩個列表並將它們相互比較?

[英]How to create two lists from an existing file and compare them to each other?

所以我有一個文件,該文件分為四個不同的類別: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分開並將它們與年份進行比較。 任何幫助都將非常有幫助!

這種“哪些名稱在該組上而不在該組上”是“集”的工作。 然后,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()

上面的代碼。

>>> 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

我發現這樣的文件有用的模式是將數據讀入第一行的標頭項索引的字典中。 使用該方法,解決方案(從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)

這種方法的優勢在於,在讀入數據后,它可以進行許多不同的數據操作,而不必擔心獲取正確的列號等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM