在for循环中调用Python变量

时间:2018-08-23 19:44:58

标签: python loops for-loop if-statement

考虑到我有三个列表,分别存储在文件sports.py中,该列表与我正在使用的.py文件分开:

games_1 = ["Tennis", …]
games_2 = ["Cricket", …] 
games_3 = ["Golf", …] 

我还有一个变量var_game == "Football"

我想检查var_game出现在哪些列表中。 到目前为止,我已经尝试过:

for N in range(1,3):
    if var_game in sports.games_N:
        gamesN_check = 1
    else:
        gamesN_check = 0

但是,Python不允许我使用N以这种方式在列表之间循环。我该如何以正确的语法使用它?

非常感谢!

3 个答案:

答案 0 :(得分:3)

我建议将您的列表包装在字典中,并按以下方式进行评估:

games_1 = ['Tennis', 'Football', 'Basketball']
games_2 = ['Cricket', 'Football', 'Lacrosse'] 
games_3 = ['Golf','Baseball', 'Rugby', 'Track'] 

games_N = {'games_1': games_1, 'games_2': games_2, 'games_3': games_3}

var_game = 'Football'

games_N_check = {key: 1 if var_game in val else 0 for key, val in games_N.items()}

输出:

{'games_1': 1, 'games_2': 1, 'games_3': 0}

另外

一种从一系列列表中创建字典的快速方法,这样您就不必显式命名每个列表:

games_lists = [['Tennis', 'Football', 'Basketball'],['Cricket', 'Football', 'Lacrosse'],['Golf','Baseball', 'Rugby', 'Track']]

games_N = {'games_{}'.format(idx+1): game_list for idx, game_list in enumerate(games_lists)}

礼物:

{'games_1': ['Tennis', 'Football', 'Basketball'], 'games_2': ['Cricket', 'Football', 'Lacrosse'], 'games_3': ['Golf', 'Baseball', 'Rugby', 'Track']}

答案 1 :(得分:0)

为什么不使用3个游戏变量,为什么不列出游戏列表

games = [["Tennis", …], ["Cricket", …], ["Golf", …]]

和结果列表

games_check = []

然后检查是否有每个game in games,如果是var_games in game,则检查-将0添加到结果列表games_check,否则添加1 < / p>

for game in games:
    if var_game in game:
        games_check.append(1)
    else:
        games_check.append(0)

或者使其更加“ Pythonic”

games_check = [(1 if var_game in game else 0) for game in games]

答案 2 :(得分:0)

我认为对于您的情况,您可以这样做:

if var_game in sports.games_1:
    games1_check = 1
elif var_game in sports.games_2:
    games2_check = 1
elif var_game in sports.games_3:
    games3_check = 1