有没有更有效的循环方法?

时间:2019-04-18 18:12:09

标签: python pyqt5

我正在制定一个房间预订程序,并且我得到了以下代码:

    def book_clicked(self):
        self._checked_items = []
        for i in range(self.tableWidget.rowCount()):
            for j in range(self.tableWidget.columnCount()):
                item = self.tableWidget.item(i, j)
                if item.checkState() == QtCore.Qt.Checked:
                    self.v = self.tableWidget.horizontalHeaderItem(j).text()
                    self.h = self.tableWidget.verticalHeaderItem(i).text()
                    self._checked_items.append([self.h, self.v, self.tableWidget.item(i, j).text()])

    def addBooking(self):
        now = QDate.currentDate()
        now1 = now.toString(Qt.DefaultLocaleLongDate)
        room,lesson,irr = zip(*self._checked_items)
        connection = sqlite3.connect("roombooking.db")
        c = connection.cursor()

        idLb = connection.execute("SELECT bookingID,lessonBooked FROM Booking WHERE dateBooked = ?",([now1]))
        idLb = idLb.fetchall()
        bID, lesBk = zip(*idLb)
        rm = connection.execute("SELECT roomNO FROM BookedRoom WHERE bookingID = ?",([bID[0]]))
        rm = rm.fetchall()
        for rooms in rm:
            print (rooms)
            if rooms == room:
                #This checks to see if the rooms in the BookedRoom table match the room that user has chosen
                for lessons in lesBk:
                    #This gets all the lessonsBooked for todays date
                    for lesson1 in lesson:
                        #This gets all the lessons that the user wants to book
                        if lessons == lesson1:
                            #If any of them match then the error shows
                            self.bookError = Ui_Dialog1()
                            self.bookError.show()
                        else:
                            ## Allow Booking ##
                            # Insert into Booking table #
                            lastBookingId = []
                            print ("Allow Booking")
                            for item in lesson:
                                c.execute("INSERT INTO Booking (lessonBooked, dateBooked, username) VALUES (?,?,?)",(item,now1,self.username))
                                connection.commit()
                                lastBookingId.append (c.lastrowid)
                            # Insert into BookedRoom table #
                            for i in range (len (lastBookingId)):
                                roomb = room[i]
                                lastBookingId1 = lastBookingId[i]
                                print (roomb)
                                print (lastBookingId1)
                                c.execute ("INSERT INTO BookedRoom (roomNO, bookingID) VALUES (?, ?)",(roomb,lastBookingId1))
                                connection.commit()

            else:
                ## Allow Booking ##

变量:

  • 房间-存储用户要预订的房间号。
  • 课程-存储他们要预订的课程时间。

我想要这段代码要做的是检查用户尝试预订的房间和时间是否已经存在于数据库中,如果是,则错误窗口将打开。但是我觉得这是一种无效的方法,因为我使用了很多for循环来遍历列表。我还希望该程序允许用户预订房间(将其添加到数据库中),如果该房间和课程时间组合不在数据库中。因此,我在else语句中这样做,但是这会使程序允许用户多次预订数据库中已经存在的房间,如输出所示:

Output

我不确定到底是什么引起的,但是我感觉这是我编写for循环的方式。

roombooking.db:

def create_user_table():
    sql = """create table User
             (username text,
             password text,
             teacher bit,
             primary key(username))"""
    create_table(db_name,"User", sql)

def create_booking_table():
    sql = """create table Booking
             (bookingID integer,
             lessonBooked text,
             dateBooked text,
             username text,
             primary key(bookingID)
             foreign key(username) references User(username))"""    
    create_table(db_name,"Booking", sql)

def create_room_table():
    sql = """create table Room
             (roomNO text,
             location text,
             roomType text,
             primary key(roomNO))"""    
    create_table(db_name,"Room", sql)

def create_bookedroom_table():
    sql = """create table BookedRoom
             (roomNO text,
             bookingID integer,
             primary key(roomNO, bookingID) 
             foreign key(roomNO) references Room(roomNO)
             foreign key(bookingID) references Booking(bookingID))"""
    create_table(db_name,"BookedRoom", sql)

1 个答案:

答案 0 :(得分:2)

我不会重写您的代码,但是会给您一些解决该问题的一般建议

  1. 如果它们是小的列表,那么您要遍历,然后将它们独立存储为列表和字典
  2. 了解列表理解。它在后台调用编译的代码,因此会更快。将适用于字典。
  3. 将您的代码分成几种方法,每种方法最多只能有一个循环。