2017-08-02 193 views
0
#room B register 
#matrix method 
roomB = [[],[]]  

我打算在这里只输入3个单位roomB =如何设置python列表上的输入限制3

def func(): 
    row = int(input("Choose 0 or 1:")) 
    if (row == 0):     # ROW 0 IS FOR HOUSE 1: 
      name = input("Enter your room name: ") 
      print("Enter M or N")  #M for master room 
      room_type = input("")   #N for normal room 
      for u in roomB:  #3 units in roomB[0] 
       if(len(u)<3): 
       if (room_type == "M"): 
        return roomB[0].append([room_type,name,140]) 
       if (room_type == "N"): 
        return roomB[0].append([room_type,name,140]) 
+0

你的问题是什么?你收到任何错误或意外的行为? –

+0

你期望输出什么? – Gahan

+0

我没有收到任何错误,但我希望我的输出在我的列表中只插入3个单位你有任何建议我应该改变吗? – Jordan

回答

0
roomB = [[],[]] 

def update(row): # takes sublist as argument 
    if len(roomB[row]) < 3: # checks if sublist length is less than 3 
     name = input("Enter your name: ") 
     room_type = input("Enter room type : M (master room) or N (normal room) : ").lower() 
     roomB[row].append([room_type,name,140]) 
     return "your room no. is {} at row {}".format(roomB[row].index([room_type,name,140]) + 1, row) # returns string stating status 


def func(): 
    if len(roomB[0]) < 3 and len(roomB[1]) < 3: # ask for prompt only if space available in both sublist 
     row = int(input("Choose 0 or 1: ")) # allow to select row 
     return update(row) 
    elif len(roomB[0]) >= 3 and len(roomB[1]) < 3: # selects default sublist if no space on other sublist 
     print("No room available at 0 , selected 1 ") 
     return update(1) # returns string stating status 
    elif len(roomB[0]) < 3 and len(roomB[1]) >= 3: # selects default sublist if no space on other sublist 
     print("No room available at 1 , selected 0 ") 
     return update(0) 
    else: # in case any error occurs it goes here 
     print("Errrr.......") 
     print("room stat....: ", roomB) 

while len(roomB[0]) <= 3 or len(roomB[1]) <= 3: # loop will flow if length of both sublist is greater than or equals to 3 
    if len(roomB[0]) != 0 or len(roomB[1]) != 0: # won't ask for confirmation if all all lists are empty (skips prompts for initial) 
     cond = input("do you want to continue?(Y/N) ").lower() 
     if cond == "n": 
      break # break the loop if pressed n or N otherwise continue to execute 
    elif len(roomB[0]) >= 3 and len(roomB[1]) >= 3: # error message to print if no space left in sublists 
     print("No room available.. Sorry for inconvinience.") 
    print(func()) 
+0

嗨谢谢你的解决方案btw我可以问为什么我们应该使用格式而不是追加?而我想要的房间只有1个主卧室和2个正常的卧室 – Jordan

+0

我已经使用append。 append只会将元素追加到列表中,因此当您编写'return list.append()'时,它(函数)将返回None。格式是在python中的字符串格式。因为我已经写它返回字符串 – Gahan

+0

你可以upvote和接受作为答案,如果有帮助 – Gahan