计算表中的类似元素

时间:2017-04-19 09:36:49

标签: python

我有一个表格,其中的数字代表分数,其中字母表就像名字一样。例如,在第一个列表中,X得分1和Y得分为1。

L = [['X','Y','1','1'],['C','A','1','2'],['X','Z','2','2']]

我的目标是在两个团队之间找到类似的结果。例如,X在第一个列表中有一个Y画面,而X在第三个列表中有一个Z画面。这使我的输出:

X: 2 (because X has 2 games of draw)
Y: 1 (because Y has 1 game of draw)
C: 0
A: 0
Z: 1 (because Z has 1 game of draw)

这是我尝试过的:

L = [['X','Y','1','1'],['C','A','1','2'],['X','Z','2','2']]
dct = {}

for i in L:

    dct[i[0]] = int(i[2])
    dct[i[1]] = int(i[3])

    if int(i[2]) == int(i[3]):
       dct[i[0]] += 0
       dct[i[1]] += 0
    else:
       dct[i[0]] = 0
       dct[i[1]] = 0

for i, occurences in dct.items():
    print(i, ':', occurrences)

它让我回答:

X:2
Y:1
C:0
A:0
Z:2 (wasn't supposed to be 2 but 1)

我的错误可能是在第6和第7行,或者我的概念可能是错误的。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你开始用

中的抽奖分数来分配抽奖数量
dct[i[0]] = int(i[2])
dct[i[1]] = int(i[3])

如果密钥0i[0])尚未在i[1]中,您应该初始化dct的那些人。

python为这类事情提供了一个很好的Counter class

from collections import Counter

score = Counter()

L = [['X','Y','1','1'],['C','A','1','2'],['X','Z','2','2']]

for lst in L:
    if lst[2] == lst[3]:
        score[lst[0]] += 1
        score[lst[1]] += 1

    # make sure we also have the zero scores
    else:
        if lst[0] not in score:
            score[lst[0]] = 0
        if lst[1] not in score:
            score[lst[1]] = 0

print(score) # Counter({'X': 2, 'Z': 1, 'Y': 1, 'A': 0, 'C': 0})

如果您不想用户Counter,请在此处修改代码:

for i in L:

    if i[0] not in dct:
        dct[i[0]] = 0
    if i[1] not in dct:
        dct[i[1]] = 0

    if i[2] == i[3]:
        dct[i[0]] += 1
        dct[i[1]] += 1