【问题标题】:working with a boolean list in python在 python 中使用布尔列表
【发布时间】:2013-03-24 02:40:46
【问题描述】:

我正在为班级制定一个锦标赛计划。该程序应该让用户输入所有团队名称,选择2个团队,并询问用户哪个团队获胜,获胜者将继续前进。我想通过使用布尔值在一个数组中完成这一切。我希望数组中的所有值都以 false 开头,如果他们获胜,则团队名称将变为 true

到目前为止我有这个

amount = int(raw_input('How many teams are playing in this tournament?   ')
teams = []
i = 0
while i < amount:
    teams.append(raw_input("please enter team name:   ")
    i = i + 1

现在,我怎样才能使整个列表false

【问题讨论】:

    标签: python list boolean


    【解决方案1】:

    在我看来,使用字典而不是列表是一种更好的方法。您只需将每个团队名称作为键添加到字典中,并将其对应的值分别设置为 FalseTrue

    amount = int(raw_input('How many teams are playing in this tournament?   ')
    teams = {}
    i = 0
    while i < amount:
        team_name = raw_input("please enter team name: ")
        teams[team_name] = False
        i = i + 1
    

    如果您想选择赢得比赛的球队,您只需在字典中查找球队名称并将其值设置为True。这样,您可以将团队名称和布尔值保留在一个数据结构中,而不需要两个数据结构或总是用根本没有意义的布尔值替换团队名称。

    【讨论】:

    • @chadybear 欢迎您。 :) 感谢您接受我的回答。
    【解决方案2】:

    既然你已经知道团队的数量(数量),你可以这样做

    team_status = [False]*amount
    

    这里,teamsteam_status 的索引是相同的,因此每次您想要特定团队的状态时都可以进行简单的查找。

    你可以用字典

    amount = int(raw_input('How many teams are playing in this tournament?   ')
    teams = {}
    for i < range(amount):
        team_name = raw_input("please enter team name:   ")
        teams.update({team_name: False})
    

    【讨论】:

    • 你确定?您仍然需要计算金额或更改退出条件
    • 这是为什么呢? amount 不是用户的输入吗?
    • 有没有办法在同一个数组中做到这一点?比如将我原始列表中的元素分配为真或假?
    • 字典列表可能是?
    • 哦,我明白了,我正在寻找一本字典。感谢您的帮助!
    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 2012-07-13
    • 2018-02-19
    • 1970-01-01
    • 2012-07-28
    • 2014-01-30
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多