【问题标题】:how to search for a variable using a string? / can you search a class for a variable?如何使用字符串搜索变量? / 你能在一个类中搜索一个变量吗?
【发布时间】:2020-10-11 08:29:28
【问题描述】:

我正在从一个文件中获取一个团队的名称,我需要一种方法来找到一个同名的变量,所有团队名称变量都在一个名为 team 的类下,有没有办法搜索变量。我不知道用字典是否会更容易。蟒蛇

class team()...

Burnley = team("Burnley",[1, 0, 0, 1], True)
Southampton = team("Southampton", [1,2,1,0,0,0,1], True)
Swansea = team("Swansea",[1,2,1,1,1,2,1,1,0,0,0,0,0,0,3],True)

df = pd.read_csv("2016-17 testing.csv")
df =df[["Date","HomeTeam","AwayTeam","FTHG","FTAG","FTR"]]

for game in df.iterrows():

    home_team = df["HomeTeam"]
    away_team = df["AwayTeam"]

在这里我需要搜索主队并找到变量。使用 for 循环是因为我们将查看结果列表并将该数据用于某些用途。 谢谢

【问题讨论】:

  • 使用字典可以帮助您解决问题。另一种可能的方法是列出所有团队。然后,您可以在此列表中搜索名称与所需名称相同的团队。
  • 另外,以大写字母开头的类名也是一个好习惯。所以,它应该被命名为Team
  • @MoosaSaadat 这个名单听起来不错,我将如何在名单中搜索主队名称?你能列出变量吗?我会改变这一点,谢谢
  • 我假设你的 team 类有一个 name 属性,它存储了团队的名称:team("Burnley",[1, 0, 0, 1], True)。就像这里一样,您传递的是团队名称"Burnley"。因此,一旦您创建了团队列表,您就可以检查 team.name 是否与名称匹配。例如,teams = [team("Burnley",[1, 0, 0, 1], True), team("Southampton", [1,2,1,0,0,0,1], True)]for t in teams:if t.name == "Burnley":

标签: python python-3.x pandas class for-loop


【解决方案1】:

最好的方法是使用字典。

teams = {
    'Burnley': team("Burnley",[1, 0, 0, 1], True),
    'Southampton': team("Southampton", [1,2,1,0,0,0,1], True),
    'Swansea': team("Swansea",[1,2,1,1,1,2,1,1,0,0,0,0,0,0,3], True)
}

# and then simply fetch values from it
Burnley = teams['Burnley']

...
for idx, game in df.iterrows():
    home_team_name = game["HomeTeam"]  # Burnley let's assume
    home_team = teams[home_team_name] 
    ...

但是,如果您真的想要问题要求的内容,请继续阅读。

假设我有一个文件,sample.py

# sample.py
from pprint import pprint

variable = 'some value'
x = 20

pprint(globals())

输出:

$ python3 sample.py 
{'__annotations__': {},
 '__builtins__': <module 'builtins' (built-in)>,
 '__cached__': None,
 '__doc__': None,
 '__file__': 'sample.py',
 '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fccad01eb80>,
 '__name__': '__main__',
 '__package__': None,
 '__spec__': None,
 'pprint': <function pprint at 0x7fccacefdf70>,
 'variable': 'some value',
 'x': 20}

如您所见,所有定义的变量都将添加到globals(),它是dict,这意味着您可以从中获取值。

因此你可以做这样的事情

# sample.py
variable = 'some value'
x = 20

variable_name = 'variable'
number_name = 'x'

value_of_variable = globals().get(variable_name)
print(f'Value of variable = {value_of_variable}')

value_of_x = globals().get(number_name)
print(f'Value of x = {value_of_x}')

输出:

Value of variable = some value
Value of x = 20

所以对于你的情况,

...

for idx, game in df.iterrows():
    home_team_name = game["HomeTeam"]  # Burnley let's assume
    home_team = globals().get(home_team_name)  # would give you the value of the variable `Burnley` if it exists
    ...

如果您已经阅读了此处的全部答案,作为建议,我想补充一点,类名应以大写字母开头。 class Team: 而不是 class team:

【讨论】:

  • 谢谢你的解释,但是当我尝试使用它时,我得到了一个('Series' objects are mutable,因此它们不能被散列)错误我不知道为什么
  • 看起来,您尝试使用 Series 对象作为字典键。您能显示发生错误的行吗?
  • home_team = globals().get(home_team)
  • df["HomeTeam"] 更改为 game["HomeTeam"]。这就是我在答案中所做的。 df["HomeTeam"] 将给出一个 pd.Series 对象,根据我的理解,这不是你想要的。
  • 我收到另一个错误,TypeError: tuple indices must be integers or slices, not str, Code is: for game in df.iterrows(): home_team_name = game["HomeTeam"] home_team = globals ().get(home_team_name) 并且错误在第 2 行 print(home_team)
猜你喜欢
  • 2014-06-16
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多