简体   繁体   中英

Python Function Append String to a list with variable name

I want to append values to the variable which is s_stat,f_stat and stat (for example for stats_players(pass), variable should be s_pass,f_pass and pass). It gives me error that s_stat is not defined. It is probally do not detect variable as s_pass.

Function

def stats_players(stat,player_id):
a = {}
b = {}
if stat != "Start" and stat != "FormationChange" :
    print(stat)
    for js in data_events[str(stat)]:
        icdType = js["playerId"]
        if icdType in a:
            a[icdType].append(js)
        else:
            a[icdType] = [js]
        
    data = json.dumps(a)
    data = json.loads(data)
    if str(player_id) in data == True:
        for js in data[str(player_id)]:
            icdType = js["outcomeType"]["displayName"]
            if icdType in b:
                b[icdType].append(js)
            else:
                b[icdType] = [js]   
        data = json.dumps(b)
        data = json.loads(data)
        if  "Successful" in data != "False":
            suc = len(data["Successful"])
            s_stat.append(len(data["Successful"]))
        else:
            suc = 0
            s_stat.append("0")
        if  "Unsuccessful" in data != "False":
            fail  = len(data["Unsuccessful"])
            f_stat.append(len(data["Unsuccessful"]))
        else:
            fail = 0
            f_stat.append("0")
        Pass.append(suc+fail)
    else:
        suc = 0
        fail = 0
        Pass.append(suc+fail)
        s_stat.append(suc)
        s_stat.append(fail)

Code

Pass = []
f_Pass = []
s_Pass = []

stats_players("Pass",player_id)

Error

Traceback (most recent call last):
File "test.py", line 446, in <module>
stats_players("Pass",player_id)
File "test.py", line 98, in stats_players
s_stat.append(suc)
NameError: name 's_stat' is not defined

You need to first declare that s_stat is a list. s_stat = [] This will let the compiler know that s_stat is a list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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