【问题标题】:How do I store a variable that has been created from a user input and use it in a different file in Python?如何存储从用户输入创建的变量并在 Python 中的不同文件中使用它?
【发布时间】:2020-11-04 20:15:32
【问题描述】:

我是 Python 新手,因此是 Stack Overflow 社区的新手。我已经开始了我的第一个迷你项目,我想从一组 6 人中随机生成一个团队并分配两个随机团队。从那里我试图创建两个文件(每个团队一个),每次一个用户可以从他们的团队中输入每个玩家的分数,最终我希望它在一个单独的文件中创建一个实时排行榜。 我已经成功创建了一个团队生成器。这就是它的精髓:

numberofplayers = int(len(online_players))

number_teams = int(input('How many teams do you want there to be?\n '))

k = int(numberofplayers/number_teams)

if numberofplayers == 6 and number_teams == 2:
    global team_1
    team_1 = random.sample(online_players, k)
    str(team_1)
    for x in team_1:
        online_players.remove(x)
        global team_2
        team_2 = online_players
    print('Team 1')
    
    print(team_1[0] +'(1)')
   
    print(team_1[1] + '(2)')
    
    print('...')
    
   print(team_1[2] +'(3)' +
                      '\n')
    
    print('Team 2')
    print(team_2[0] + '(4)')
   
    print(team_2[1]+ '(5)')
    
    print(team_2[2]+ '(6)')

这样就成功生成了两个3人的团队。这个文件叫做Team_Generator.py

在我使用的另一个名为 team_1_input.py 的文件中

from Team_Generator.py import team_1,team_2
print(team_1)

当我在控制台中运行它时,它会再次执行整个团队生成器流程,而不仅仅是使用 Team_Generator.py 中已经分配的团队

对如何让它工作以使 team_1_input.py 识别从 Team_Generator.py 分配的团队有任何见解吗?

谢谢

【问题讨论】:

    标签: python file variables global-variables


    【解决方案1】:

    如果这段代码也是你程序的起点,你应该用:

    if __name__ == "__main__":
        # your code here
    

    在导入模块时会阻止它运行。

    但是,通过导入您的主入口点,您创建了一个循环依赖:您的主文件依赖于另一个依赖于主文件的文件!它可以工作,但会让你的生活变得不必要地复杂。

    相反,您绝对应该让您的其他文件公开一个将团队作为参数的函数,并让主文件调用它。

    def do_something_about_teams(team_1, team_2):
        print(team_1)
    

    在你的主文件中:

    from otherfile import do_something_about_teams
    
    # beginning of main, etc...
    
    do_something_about_teams(team_1, team_2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      相关资源
      最近更新 更多