【问题标题】:How am I able to count how many specific string values of a certain kind I have in my list / dictionary?我如何计算我的列表/字典中有多少特定类型的特定字符串值?
【发布时间】:2021-05-18 23:05:15
【问题描述】:

这里完全是新手,名声缓慢但肯定会越来越差。我想知道我的字典值 char['bag']['Iron Ingot'] 或任何 'Ingot' 在不显示 TypeError 的情况下如何计算:'list indices must be integers or slices, not str. ' Counter 似乎不起作用,因为它没有解决我要计算的字符串而不是 int 的事实。我想计算这个字符串并输出一个整数值 - 我在列表中拥有的所述字符串的数量。

char = {'name' : 'Hero',
    'lv': 3,
    'xp': 0,
    'lvnext': 83,
    'gp' : 1225,
    'bag' : ["Bronze Bastard", "Iron Ingot"],
    'stats' : {'ATT': 111,
                'DEF': 1,
                'WIS': 1,
                'hp' : 100,
                'atk' : [5,22]}}



def blacksmith():
print("The Master Smith is a giant-like abomination of a demon.")
print("Smith: Bring me ingot, and gold piece, and I will bend the metal to your liking.")
print("[1 ingot per Claw/Claymore/Helm/Gauntlets/Boots, 2 ingots per Bastard/Chain-whip, 4 ingots per Full suit/Liquid coat]")
print("[X ingot(s)] ")
item = input("Assuming you have the ingot and coin, I can make anything forged from the Titanite anvil. (Correctly type the item you want forged.)")
if item == "Iron Claws" and char['bag'].count("Iron Ingot") >= 1 and char['gp'] >= 15:
    char['bag'].append(item)
    char['bag'] - char['bag']['Iron Ingot']
    char['gp'] = char['gp'] - 15
    char['stats']['atk'][:] = [x + 1 for x in char['stats']['atk']]
    print("{} has been added to your bottomless bag!".format(item))
    chapterOne()

【问题讨论】:

    标签: python python-3.x text text-based


    【解决方案1】:

    尝试了你的代码后,我发现错误是因为使用了这个

    char['bag']['Iron Ingot']
    

    发生错误是因为您只能使用int 访问列表内的元素。 char['bag'] 的类型是 list 因此,你不能这样做。

    要计算列表中的元素,您可以简单地使用Counter,要做到这一点,您只需像下面这样导入它

    import collections
    
    # Make a Counter object
    count_object = collections.Counter(char['bag'])
    
    # Before printing out, convert it to dict
    print(dict(count_object))
    

    您可以进行一些更改以使您的功能正常工作!

    【讨论】:

    • 感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多