使用字符串作为变量名 Python [英] Use String as Variable Name Python

查看:153
本文介绍了使用字符串作为变量名 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作棒球数据和阵容的数据库.有没有办法遍历团队列表并使用字符串作为变量名?

I am trying to make a database of baseball stats and lineups. Is there a way to loop through a list of teams and use a string as an variable name?

例如:提取团队名称

team_name = 'BOS'

使用 BOS 作为对象的变量名并附加到对象列表

Use BOS as variable name for object and append to list of objects

BOS = team_data()
teams.append(BOS)

然后当我索引一些统计数据时,我可以执行以下操作来检索阵容:

Then when I index some stats, I can do the following to retrieve the lineup:

teams.BOS.lineup

我知道在 Matlab 中您可以执行以下操作,我想知道 Python 中是否有等效项:

I know in Matlab you can do the following and I was wondering if there is an equivalent in Python:

teams.(team_name).lineup

目前我让它在每个循环中将数据分配给相同的变量名并附加到列表中.

Currently I have it assigning the data to the same variable name each loop and appending to the list.

teams[0].team_name = 'BOS'
teams[1].team_name = 'NYY'

我唯一的想法是为 team_name 分配一个 switch case 来分配给 team 变量名.

My only other thought is to have a switch case for team_name to assign to the team variable name.

推荐答案

使用字典:

teams = {}

teams['BOS'] = team_data()   
teams['NYY'] = team_data() 

for key in teams:
    print(teams[key].team_name) # removed the quotes around "key"

这篇关于使用字符串作为变量名 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆