简体   繁体   English

在python字典中添加和访问键值

[英]Adding and accessing values to key in python dictionary

I'm writing a python script that reads a players name and stats from a sentence in a .txt file, then updates their stats within a dictionary and then prints out their average stats. 我正在编写一个python脚本,该脚本从.txt文件中的句子中读取玩家的名字和状态,然后在字典中更新其状态,然后打印出其平均状态。 I'm having trouble with assigning multiple values to the same 'player' key, as well as getting the logic below it to correctly update the player stats. 我在为同一个“玩家”键分配多个值时遇到麻烦,并且无法获得逻辑之下的值来正确更新玩家统计信息。 The .group part is giving me trouble too. .group部分也给我带来了麻烦。 How can I do this? 我怎样才能做到这一点?

  import re, sys, os, math

if len(sys.argv) < 2:
    sys.exit("Usage: %s filename" % sys.argv[0])

filename = sys.argv[1]

if not os.path.exists(filename):
    sys.exit("Error: File '%s' not found" % sys.argv[1])

line_regex = re.compile(r"^(\w+ \w+) batted (\d+) times with (\d+) hits and (\d+) runs")
line = [line.strip() for line in open(filename)]

f = open (filename)

playerStats = {'players': [0, 0, 0]} 

for players in playerStats:
    player = line.group(1)
    atBat = line.group(2)
    hit = line.group(3)

    if player in playerStats:
            playerStats[player][0] += atBat
            playerStats[player][1] += hit

    if player not in players:
        player = line.group(1)
        playerStats[player][0] = atBat
        playerStats[player][1] = hit
        avgs = 0

    else: 
        playerStats[player][0] = player
        playerStats[player][0] = atBat
        playerStats[player][1] = hit
        playerStats[player][2] = 0

for player in players:
    avgs[player] = round(float(hits[player])/float(atBats[player]), 3) 

print "%s: %.3f" % (player, avgs[player])

Traceback (most recent call last): File "ba.py", line 19, in player = line.group(1) AttributeError: 'list' object has no attribute 'group' 追溯(最近一次通话最后一次):文件“ ba.py”,行19中的播放器= line.group(1)AttributeError:“列表”对象没有属性“组”

You should change this 你应该改变这个

playerStats = {'players': hits, atBats, avgs} 

To

playerStats = {'players': [0, 0, 0]} 

The latter stores the value as a list , the former is not valid Python syntax. 后者将值存储为list ,前者无效的Python语法。

To modify one of these values you would do, for example 例如,要修改这些值之一,您可以执行

playerStats[player][1] = 5   # atBat value

You could also change to a nested structure like 您还可以更改为嵌套结构,例如

playerStats = {'players': {'hits' : 0,
                           'atBats' : 0,
                           'avgs' : 0)}

Then you could modify the values as 然后您可以将值修改为

playerStats[player]['hits'] = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM