如何为列表中某个项的某些实例生成只在for循环中注册的elif命令?

2024-07-07 07:07:21 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的部分代码。基本上,当运行它时,它会创建一个随机数、给定货币代码和信用卡限额的信用卡。信用卡是一个类,它存储的钱也是一个类(为了简洁起见,我没有把它包括在这里,因为我认为它们与我的问题无关),我的取消声明很好,但如果我有两张信用卡在一个名单,我试图取消第二个它会再次打印没有这样的卡。如果卡片在列表中,它将被删除。我猜是因为for循环遍历列表,它首先检测到一张卡的编号与给定的不同,这就是为什么它不打印这样的卡的原因,但我不知道如何解决这个问题。我们将不胜感激。你知道吗

PATH = 'saved_cards.txt'
creditcard_list = []
import decimal
import ast
import collections
import os
import random


def currency_dictionary():
    '''Initialized at the start of the program. It finds and reads a currency.txt
       file and stores those in a dictionary'''
    final_dict = collections.defaultdict(list)
    with open("currency.txt", 'r') as f:
        currency_lines = f.readlines()
    for item in currency_lines:
        m = item.split(' ')
        final_dict[m[0]] = [int(m[1]), decimal.Decimal(m[2])]
    return final_dict





class Money():
    def __init__(self, money_amount: decimal, currency_code: str):
        self.m = decimal.Decimal(money_amount)
        self.c = str(currency_code)
        self.d = currency_dictionary()


def __repr__(self):
    return 'Money({}, {})'.format(self.m, self.c)

def __eq__(self, other):
    if type(other) != Money:
        return False

    elif self.c == other.c:
        return self.m == other.m

    elif self.c != other.c:
        dictionary_key1 = self.d[self.c]
        decimal_point1 = dictionary_key1[0]
        conversion_factor1 = dictionary_key1[1]
        x = self.m / conversion_factor1

        dictionary_key2 = self.d[other.c]
        decimal_point = dictionary_key2[0]
        conversion_factor = dictionary_key2[1]
        y = other.m / conversion_factor

        return x == y

def __ne__(self, other):
    if type(other) != Money:
        return True

    elif self.c == other.c:
        return self.m != other.m

    elif self.c != other.c:
        dictionary_key1 = self.d[self.c]
        decimal_point1 = dictionary_key1[0]
        conversion_factor1 = dictionary_key1[1]
        x = self.m / conversion_factor1

        dictionary_key2 = self.d[other.c]
        decimal_point = dictionary_key2[0]
        conversion_factor = dictionary_key2[1]
        y = other.m / conversion_factor

        return x != y

def __add__(self, other):
    if self.c == other.c:
        return Money((self.m + other.m), self.c)

    elif self.c != other.c:
        dictionary_key1 = self.d[self.c]
        decimal_point1 = dictionary_key1[0]
        conversion_factor1 = dictionary_key1[1]
        x = self.m / conversion_factor1

        dictionary_key2 = self.d[other.c]
        decimal_point = dictionary_key2[0]
        conversion_factor2 = dictionary_key2[1]
        y = other.m / conversion_factor2

        total = x + y
        return Money((total * conversion_factor1), self.c)


def __sub__(self, other):
    if self.c == other.c:
        return Money((self.m - other.m), self.c)

    elif self.c != other.c:
        dictionary_key1 = self.d[self.c]
        decimal_point1 = dictionary_key1[0]
        conversion_factor1 = dictionary_key1[1]
        x = self.m / conversion_factor1

        dictionary_key2 = self.d[other.c]
        decimal_point = dictionary_key2[0]
        conversion_factor2 = dictionary_key2[1]
        y = other.m / conversion_factor2

        total = x - y
        return Money((total * conversion_factor1), self.c)

class Credit_Card():
    def __init__(self, card_number, money_amount: Money, card_limit: int):
        if type(money_amount) != Money or type(card_limit) != int:
            raise TypeError('one of the types of the parameters entered is not valid')
        self.number = card_number
        self.amount = money_amount
        self.limit = card_limit

def __repr__(self):
    return 'Card#{}({}, {})'.format(self.number, self.amount, self.limit)

def user_interface():
    boolean = True

    while boolean:
        temp_list = []
        command = input()
        if command.split()[0] == 'ISSUE':
            if len(command.split()) == 3:
                x = "%0.5d" % random.randint(0,99999)
                currency_code = command.split()[1]
                card_limit = int(command.split()[2])
            if card_limit < 0:
                print("NEGATIVE_LIMIT")
            elif not currency_dictionary()[currency_code]:
                print("NO_SUCH_CURRENCY")
            else:
                for card in creditcard_list:
                    temp_list.append(card.number)
                if x not in temp_list and currency_dictionary()[currency_code]:
                    creditcard_list.append(Credit_Card(x, Money(0, currency_code), card_limit))
                    print('ISSUED', x)
                    print(creditcard_list)

        else:
            print("INVALID_ISSUE_COMMAND")


    elif command.split()[0] == 'CANCEL':
        templist2 = []
        if len(command.split()) == 2:
            card_number = command.split()[1]

            for card in creditcard_list:
                templist2.append(card)
            for i, card in enumerate(templist2):
                if card_number not in templist2[i].number:
                    print('NO_SUCH_CARD')
                elif templist2[i].amount.m != 0:
                    print('NONZERO_BALANCE')
                elif templist2[i].number == command.split()[1] and card.amount.m == 0:
                    del creditcard_list[i]
                    print('CANCELLED', card_number)


            print(creditcard_list)


    elif command.split()[0] == 'PURCHASE':
        if len(command.split()) == 4:
            card_number = command.split()[1]
            currency_code = command.split()[2]
            amount = int(command.split()[3])
            if currency_code not in currency_dictionary().keys():
                print('NO_SUCH_CURRENCY')
            elif amount < 0:
                print('NONPOSITIVE_AMOUNT')
            else:
                for i, card in enumerate(creditcard_list):
                    if card.number == card_number and 0 <= amount <= card.limit :
                        x = card.amount + Money(amount, currency_code)
                        creditcard_list[i] = Credit_Card(card.number, x, card.limit)
                    elif creditcard_list[i].number != card_number:
                        print('NO_SUCH_CARD')
                    elif amount > creditcard_list[i].limit:
                        print('OVER_LIMIT')

    elif command.split(0) == 'PAYMENT':


            print(creditcard_list)



if __name__ == '__main__':
    user_interface()

我对cancel命令的输出基本上是这样的,我很确定一旦我弄明白了这一点,我就能处理剩下的。粗体输入,非粗体输出。你知道吗

**ISSUE USD 5000**
ISSUED 50695
[Card#50695(Money(0, USD), 5000)]
**ISSUE RON 3000**
ISSUED 25282
[Card#50695(Money(0, USD), 5000), Card#25282(Money(0, RON), 3000)]
**CANCEL 25282**
[Card#50695(Money(0, USD), 5000), Card#25282(Money(0, RON), 3000)]
*NO_SUCH_CARD*
CANCELLED 25282
[Card#50695(Money(0, USD), 5000)]

请注意,这些列表只打印出来,以便我跟踪主列表中当前有哪些卡片,我最终将删除这些打印语句。我把有问题的输出斜体化了。你知道吗


Tags: selfnumberdictionaryifcardamountcurrencycommand
1条回答
网友
1楼 · 发布于 2024-07-07 07:07:21

问题似乎是您在迭代它的同时修改了creditcard_list。您应该首先创建一个列表的临时副本以进行迭代,然后从实际列表中删除项。你知道吗

编辑:啊,它在列表的第一张卡片上打印“没有这样的卡片”!不是第二次。所以在你的例子中,你循环一个有两个的列表;它首先访问卡片#50695,它不等于2582,所以它打印“没有这样的卡片”。然后它访问25282,删除它,并打印“cancelled”。它做的正是你写它的目的。相反,只要循环通过,删除卡如果你找到它,并悄悄跳过任何卡不匹配。最后,如果找不到卡,打印“没有这样的卡”

Edit2:举个例子:

        found = False
        for card in templist2:
            if card_number == card.number:
                if card.amount.m != 0:
                    print('NONZERO_BALANCE')
                else:
                    del creditcard_list[i]
                    print('CANCELLED', card_number)
                found = True
                break
        if not found:
            print('NO_SUCH_CARD')

相关问题 更多 >