【问题标题】:i want to print out a certain part of a list我想打印出列表的某个部分
【发布时间】:2022-01-18 12:08:06
【问题描述】:

所以我有一个包含一个对象的列表,但我想用它做一个搜索算法,这意味着如果单词相似,它将显示具有相似类别的项目。但是出现了错误。

代码:

print("\nHere are the results of your search")
    if param == 'Electric Guitar':
        results = inventory[item_006:item_010] 

对象:

class Product:

    def __init__(self, hproduct, htype, hprice, havail):
        self.name = hproduct
        self.type = htype
        self.price = hprice
        self.avail = havail
    def __eq__(self,other):
        return self.type == other

item_001 = Product('Tyma TD-10E Dreadnought', 'Acoustic Guitar', 23450, 'In Stock')
item_002 = Product('Baton Rouge AR21C/ME Traveler', 'Acoustic Guitar', 14900, 'In Stock')
item_003 = Product('Phoebus Baby 30 GS Mini', 'Acoustic Guitar', 6900, 'In Stock')
item_004 = Product('Maestro Project X X1-V1 OM', 'Acoustic Guitar', 32500, 'In Stock')
item_005 = Product('Sire A4 Grand Auditorium', 'Acoustic Guitar', 27490, 'In Stock')

item_006 = Product('Tagima TW55', 'Electric Guitar', 9500, 'In Stock')
item_007 = Product('Epiphone G400 ', 'Electric Guitar', 19500, 'In Stock')
item_008 = Product('D’Angelico Premiere DC', 'Electric Guitar', 49000, 'In Stock')
item_009 = Product('PRS Silver Sky', 'Electric Guitar', 138950, 'In Stock')
item_010 = Product('Vintage V100 Reissued', 'Electric Guitar', 27950, 'In Stock')

item_011 = Product('Phoebus Buddie 30 GS-E', 'Bass Guitar', 8720, 'In Stock')
item_012 = Product('Sire U5', 'Bass Guitar', 27490, 'In Stock')
item_013 = Product('Lakland Skyline Vintage J', 'Bass Guitar', 82950, 'In Stock')
item_014 = Product('Schecter Model T Session 5', 'Bass Guitar', 45900, 'In Stock')
item_015 = Product('Tagima Millenium Coda 4', 'Bass Guitar', 14900, 'In Stock')

item_016 = Product('Boss Katana 50 Mk II ', 'Accessory', 15950, 'In Stock')
item_017 = Product('TC Electronic BH250 Micro Bass', 'Accessory', 18990, 'In Stock')
item_018 = Product('Kemper Profiler Powerhead', 'Accessory', 130000, 'In Stock')
item_019 = Product('Headrush Pedal Board', 'Accessory', 27490, 'In Stock')
item_020 = Product('NUX MG30', 'Accessory', 12900, 'In Stock')

inventory = [item_001, item_002, item_003, item_004, item_005, item_006, item_007, item_008, item_009, item_010, item_011, item_012, item_013, item_014, item_015, item_016, item_017, item_018, item_019, item_020]

想要的输出:

Tagima TW55                         Electric Guitar              9500     In Stock
Epiphone G400                       Electric Guitar              19500    In Stock
D’Angelico Premiere DC              Electric Guitar              49000    In Stock
PRS Silver Sky                      Electric Guitar              138950   In Stock
Vintage V100 Reissued               Electric Guitar              27950    In Stock

错误:

slice indices must be integers or None or have an __index__ method

感谢您的任何提示和帮助。

【问题讨论】:

  • 什么是alist
  • 存储对象的列表
  • 我编辑了它@LeopardShark
  • inventory[5:10]?

标签: python search


【解决方案1】:

由于您需要匹配类型等于参数的所有对象,因此您可以做一些比硬编码结果位置更动态的事情:

results = [obj for obj in inventory if obj.type == param]

【讨论】:

    【解决方案2】:
    slice indices must be integers or None or have an __index__ method
    

    这意味着您应该在您的对象中实现__index__ 魔术方法。 __index__ 需要返回整数,在您的情况下,位置在 list。考虑以下简单示例

    class Thing:
        def __init__(self, name):
            self.name = name
        def __repr__(self):
            return 'Thing("' + self.name + '")'
        def __index__(self):
            return inventory.index(self)
    uno = Thing("uno")
    dos = Thing("dos")
    tres = Thing("tres")
    inventory = [uno,dos,tres]
    print(inventory[:dos])
    print(inventory[dos:])
    print(inventory[dos:tres])
    

    输出

    [Thing("uno")]
    [Thing("dos"), Thing("tres")]
    [Thing("dos")]
    

    免责声明:此解决方案假定您的所有对象都保存在一个列表中。

    【讨论】:

      【解决方案3】:

      这种行为的原因是您正在使用inventory[item_006:item_010] 中的对象item_006item_010 对列表进行切片,而切片使用下面提到的索引

      [开始:停止:步骤]

      这意味着切片将从索引开始将上升到 一步一步停下来。 start 的默认值为 0,stop 为 last 列表索引,步骤为 1

      要获得所需的输出,只需执行以下操作:

      param = "Electric Guitar"
      results = [item for item in inventory if item.type == param]
      print (results)
      

      【讨论】:

        【解决方案4】:

        对你所做的最直接的修复就是这个。

        results = inventory[5:10]
        

        你必须给切片整数作为索引,而不是Products。

        但是,在您的情况下,最好简单地查找具有type"Electric Guitar" 的产品:

        results = [p for p in inventory if p.type == "Electric Guitar"]
        

        如果你的完整代码最终看起来像

        if param == "Electric Guitar":
            results = [p for p in inventory if p.type == "Electric Guitar"]
        elif param == "Acoustic Guitar":
            results = [p for p in inventory if p.type == "Acoustic Guitar"]
        ...
        

        那么您可以将其简化为:

        if param in {"Electric Guitar", "Acoustic Guitar", ...}:
            results = [p for p in inventory if p.type == param]
        

        【讨论】:

        • 当我尝试其他类型如原声吉他时,它显示'str' object has no attribute 'price'
        • @PythonnLearner 你到底做了什么?
        • 我在我的代码中实现了这个def binary(word, sett): first = 0 last = len(sett) - 1 asd = False while first<=last and not asd: mid = (first + last)//2 if sett[mid].__eq__(word): asd = True return True else: if word < sett[mid]: last = mid - 1 else: first = mid + 1
        • @PythonnLearner 这只是一个二分搜索算法,不应该导致AttributeError。错误应该来自你做something.price的地方。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-18
        • 2011-01-14
        • 2017-07-04
        • 1970-01-01
        • 2020-07-18
        相关资源
        最近更新 更多