2015-10-17 18 views
1

我想讓我的代碼只輸入7個項目,當輸入7時循環結束。但是下面的代碼目前沒有這樣做。如何使用while循環同時檢查列表中的項目

這裏是我的代碼:

def occupants(): 
    oc = [0]*8 
    while len(oc) <= 7: 
     x = int(input("Enter a number")) 
     oc.append(x) 
     if len(oc) == 8: 
      break 

回答

2

開始對空列表。否則循環體將不會運行,因爲已經有8個元素。

oc = [] 

while len(oc) < 7: # `<=` -> `<` 
    x = int(input("Enter a number")) 
    oc.append(x) 

而且,條件應該調整。否則,它會得到一個項目(8)。

0

你的代碼不工作的原因是因爲你從一個已經包含7個以上項目的列表開始,所以while循環將在它開始之前完成。其次,break條件是不必要的,因爲while循環將在True之前結束。

除非用例是比在問題給出的示例更復雜,簡單的列表理解可以實現這樣的結果:

oc = [int(input("Enter a number")) for x in xrange(7)] 

這將運行整整7輸入,僅需要一個單一的代碼行,並在我看來更清晰和pythonic。

1

你想要一個空的列表,這樣你就可以在每次迭代中追加一些東西,並且在7次迭代之後你想打破這個循環。很簡單。

現在,讓我們看看你的意見。

>>oc = [0]*8 
>>oc 
[0, 0, 0, 0, 0, 0, 0, 0] 
>>len(oc) 
>>8 

所以,你基本上創建元件,其每一個的8的列表是0與線[0]*8

while len(oc) <= 7: #This will never be true because len(oc) is 8 already. 

因此,採取一個空列表[]。下面的代碼將工作。

def occupants(): 
    oc = [] 
    while len(oc) < 7: 
     x = int(input("Enter a number")) 
     oc.append(x) 
0

你只需要反正重新檢查你的邏輯,你可以寫你的代碼像下面

def occupants(): 
    oc = [] 
    while len(oc) < 7: 
    x = int(input("Enter a number")) 
    oc.append(x) 
    print oc 

你循環運行,直到「OC」的長度爲6,在「LEN (oc)= 6「it 將進入循環追加第7個元素,並且當」len(oc)= 7「時,它將不會進入循環。