列表和dictinarys不在if / elif语句中工作

时间:2013-09-08 10:05:15

标签: python list function if-statement dictionary

继承人代码:

def resetInv(inventory):
    if type(inventory) == list:
        inventory=[]
        return(inventory)
    elif type(inventory) == dict:
        return({})
    elif type(inventory) == str:
        return('nothing in inventory')
    elif type(inventory) == bool:
        return(False)
    else:
        return('not inventory type')

适用于str和bool,但不适用于列表和词典。

1 个答案:

答案 0 :(得分:1)

一些提示:

  • PEP8建议为函数使用underescored_names(而不是camelCaseNames)
  • 不要使用类型,如果必须检查类型,请使用isinstance函数
  • 检查类型通常是Python中的代码气味 - 使用duck-typing或更改算法

这对我有用:

>>> def reset_inv(inventory):
    if isinstance(inventory, list):
        return []
    elif isinstance(inventory, dict):
        return {}
    elif isinstance(inventory, str):
        return 'nothing in inventory'
    elif isinstance(inventory, bool):
        return False
    else:
        return 'not inventory type'


>>> reset_inv([1, 2, 3])
[]

>>> reset_inv({"a": 1})
{}

>>> reset_inv("foo")
'nothing in inventory'

>>> reset_inv(True)
False

>>> reset_inv(0.1)
'not inventory type'

编写库存系统的惯用方法可能是使用普通列表或dict作为对象的容器。下面我正在使用字符串,但您应该为库存项目编写一个类,其中包含值,重量等属性。

>>> from collections import Counter

>>> class Inventory(object):
    def __init__(self, items = None):
        if items is None:
            self.reset()
        else:
            self.items = items

    def reset(self):
        self.items = []

    def report(self):
        if not self.items:
            print("Your sac is empty.")
            return

        print("You have {} items in your sac.".format(len(self.items)))
        counter = Counter(self.items).items()
        for count, item in counter:
            print("{: >3} {}".format(item, count))


>>> inv = Inventory(['knife', 'rock', 'rock', 'cloth'])

>>> inv.report()
You have 4 items in your sac.
  1 cloth
  1 knife
  2 rock

>>> inv.items.append('coin')

>>> inv.report()
You have 5 items in your sac.
  1 cloth
  1 coin
  1 knife
  2 rock

>>> inv.items.remove('rock')

>>> inv.report()
You have 4 items in your sac.
  1 cloth
  1 coin
  1 knife
  1 rock

>>> inv.reset()

>>> inv.report()
Your sac is empty.