簡體   English   中英

有沒有更有效的循環方法?

[英]Is there a more efficient way to use for loops?

我正在制定一個房間預訂程序,並且得到以下代碼:

    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語句中執行了此操作,但是這導致程序允許用戶多次預訂數據庫中已經存在的房間,如輸出所示:

輸出量

我不確定到底是什么導致了這種情況,但是我感覺這是我編寫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. 如果它們只是小列表,那么您要進行遍歷,然后將它們獨立存儲為列表和字典
  2. 了解列表理解。 它在后台調用編譯的代碼,因此會更快。 將適用於字典。
  3. 將您的代碼分成幾種方法,每種方法最多只能有一個循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM