【问题标题】:How to fix "list.remove[x] : x not in list如何修复“list.remove[x]:x不在列表中
【发布时间】:2019-08-29 01:25:12
【问题描述】:

我正在尝试构建我的第一个真正的个人项目,这是我在这里的第一篇文章。这是一个龙与地下城的角色构建器。我在从列表中删除项目时遇到问题。

我已经成功地创建了一个滚动统计数据的函数,但不可否认的是,这很混乱。它掷出 4 个 6 面骰子并取前 3 个掷骰子,然后总计 6 次得到一个统计数组。然后,我尝试创建第二个函数,允许用户从第一个函数中获取卷,并将它们应用于游戏中的统计名称,并将它们从原始列表中删除。

print("Dungeons and Dragons 5e Character Creator")
import random

def stats_roll():

这真的很混乱而且很长。它所做的只是将数字放入变量列表“stats”

stats_roll()
edit_stats = stats


def stat_assignment():
    global str
    global dex
    global con
    global intel
    global wis
    global cha
    print (edit_stats)
    str = input("Which stat will you assign to Strength?: ")
    int(str)
    edit_stats.remove(str)

我想要的是在stat_assignment 函数中从edit_stats 中一一获取统计数据并将它们删除并将它们应用到用户想要它们的统计数据的新变量中。我得到一个@ 987654325@错误。

【问题讨论】:

  • str是python中的字符串类型,不要用这个作为变量名。如果您确实想要所有这些状态变量,您可以考虑使用class 来保存它们。您对edit_stats 列表有什么期待?您不太可能拥有 str 的值,也许您的意思是 str 作为索引,例如del edit_stats[str]
  • 发布带有完整回溯的完整错误消息。你在哪里定义statsint(str) 也不会做任何事情,除非你将返回值分配给某物。
  • int(str) 没有做任何事情 - 它的返回值应该分配给某物...something = int(str)

标签: python list


【解决方案1】:

如果您想避免错误,您可以过滤元素(请不要将变量称为 python 内置函数!):

edit_stats = [1,2,3,4,5]

str_ = "4"

edit_stats = [x for x in edit_stats if x != int(str_)]

print(edit_stats)

结果:

[1,2,3,5]

更漂亮的是,你可以告诉用户发生了什么:

edit_stats = [1,2,3,4,5]

str_ = input("Which stat will you assign to Strength?: ")

if(str_ in edit_stats):
  edit_stats = [x for x in edit_stats if x != int(str_)]
  print(str_ + " deleted!")
else:
  print(str_ + " doesn't belong to list")

【讨论】:

  • 我没想到 str 是内置的!我把它改成了“力量”,谢谢!我这样做的方式是我想从用户输入中删除数字。此外,您建议的方式不会删除 str_ 变量的所有实例,所以如果有重复(由于统计列表是随机的而经常发生),是否不会删除所有实例?对不起初学者的问题。我什至不知道您使用的方法:S
  • @HogHoncho 你想删除输入的所有实例吗?还是第一个?
【解决方案2】:

字典更适合您的需求,而不是使用列表;唯一的问题是标准字典是 not 有序的,这意味着如果您循环浏览其项目,您将永远不会获得相同顺序的键/值对。标准库模块提供了OrderedDict,这是一个高级类,可以像字典一样工作,同时始终记住插入数据的顺序。

除了建议和明智的建议“不要将内置函数用作变量名”之外,您应该真正避免变量名中的“字符廉价”:它们对可读性没有帮助和调试:使用太短的名称“获得”的十分之一秒很容易变成痛苦的寻找错误的几分钟(如果不是几小时!)。
最后,global 语句应该只在非常特殊的情况下使用,它的使用率很高discouraged

import random
from collections import OrderedDict

# create the valid range for every ability, while keeping the insertion order;
# it's been more than 20 years since I've played tabletop role playing, these
# are just ranges I put in randomly
ability_ranges = OrderedDict([
    ("Strength", (3, 20)), 
    ("Dexterity", (5, 18)), 
    ("Constitution", (2, 20)), 
    ("Intelligence", (3, 18)), 
    ("Wisdom", (1, 18)), 
    ("Charisma", (4, 16)), 
])

print("Dungeons and Dragons 5e Character Creator\n")

def stats_roll():
    # create a new dictionary object that will be filled in with new statistics
    stats = {}
    for ability, (minimum, maximum) in ability_ranges.items():
        # create random statistics, remember that randrange is always between
        # the minimum and the maximum *minus* one: randrange(0, 2) will only
        # return 0 or 1
        stats[ability] = random.randrange(minimum, maximum + 1)
    # return the complete statistics
    return stats

stats = stats_roll()

def stats_assignment(stats):
    print("Current stats:")
    for ability in ability_ranges.keys():
        while True:
            # use a while loop to avoid raising exceptions if the user does not
            # input a number or the number is not between the range of the ability
            random_value = stats[ability]
            ability_min, ability_max = ability_ranges[ability]
            new_value = input("Which stat will you assign to {} (current: {}, <Enter> to confirm)? ".format(
                ability, random_value))
            if not new_value:
                # if the user presses <Enter> without typing anything it means
                # that he/she is ok with the random chosen value
                stats[ability] = random_value
                break
            if new_value.isdigit():
                new_value = int(new_value)
                if ability_min <= new_value <= ability_max:
                    # if the value is between the allowed range, use it and go on!
                    stats[ability] = new_value
                    break
            # at this point the user has entered a value outside the allowed range
            # or has typed something that cannot be interpreted as a number
            print("{} is not a valid value for {} (has to be between {} and {})!\n".format(
                new_value, ability, ability_min, ability_max))

# run the assignment function using the existing statistics as a parameter; the
# function will modify the data of the "stats" object in place
stats_assignment(stats)

print("\nYour character statistics:")
for key in ability_ranges.keys():
    print("  {}: {}".format(key, stats[key]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-17
    • 2018-07-05
    • 1970-01-01
    • 2022-01-12
    • 2019-03-15
    • 1970-01-01
    • 2021-01-21
    • 2014-08-14
    相关资源
    最近更新 更多