【问题标题】:Accessing the elements of tuple访问元组的元素
【发布时间】:2020-08-20 11:07:01
【问题描述】:

这个问题需要很少的空格分隔输入(将它们分成一个元组列表)并返回产品的总成本乘以其数量。 在解决这个问题时,我陷入了Cost 的方法中。这并没有给我正确的输出。

我面临的问题:

  1. 成本法没有给我产品价格的总和
  2. 如果我打印元组列表 - print(part2.create_list_of_tuples()) ;我得到了意想不到的元组列表。示例 -

我给定的输入-

输入公式 - sl.no.<space>product<space>quantity<space>price

Enter an entry: 1 book 3 20
Enter an entry: 2 pen 10 5
Enter an entry: 3 notebook 10 10
Enter an entry: 0

输出-

[(1, 'book', 3, 20), (1, 'book', 3, 20), (2, 'pen', 10, 5), (1, 'book', 3, 20), (2, 'pen', 10, 5), (3, 'notebook', 10, 10)]

实际输出应该是-

Product price 210
[(1, 'book', 3, 20), (2, 'pen', 10, 5), (3, 'notebook', 10, 10)]

谁能帮我解决这个问题?

class products:
    def __init__(self):
        self.sl_no = list()
        self.item_name = list()
        self.purchase_amount = list()
        self.purchase_cost = list()
        self.list_of_tuples = list()

    def create_list_of_tuples(self):
        self.list_of_tuples = list(zip(self.sl_no, self.item_name, self.purchase_amount, self.purchase_cost))
        return self.list_of_tuples


    def Cost(self):
        Sum_purchase_cost = 0
        for j in self.list_of_tuples:
            Sum_purchase_cost += ((j[2]) * (j[3]))
        print(f"Product price {Sum_purchase_cost}")

part2=product()
tuplelist = []
while True:
    a = input('Enter an entry: ')
    if a == str(0):
        break
    tuplelist.append(tuple(a.strip().split()))
    for i in tuplelist:
        part2.sl_no.append(int(i[0]))
        part2.item_name.append(i[1])
        part2.purchase_amount.append(int(i[2]))
        part2.purchase_cost.append(int(i[3]))
part2.Cost()
print(part2.create_list_of_tuples())

【问题讨论】:

标签: python oop


【解决方案1】:

每次添加新元素时,都会为 tuplelist 中已存在的每个元素执行内部 for 循环。

要么取消缩进该循环(使其只运行一次),要么将新创建的元组存储在变量 i 中并删除 for 循环语句(但不是循环体)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多