0
我無法添加列表中的所有元素。僅添加最後一個元素。我怎樣才能添加所有輸入的元素?將元素添加到用戶列表
N = input("Enter the number of elemets: ")
for i in xrange(N):
N = []
a = input('%d. Element: ' %(i+1))
N.append(a)
print N
我無法添加列表中的所有元素。僅添加最後一個元素。我怎樣才能添加所有輸入的元素?將元素添加到用戶列表
N = input("Enter the number of elemets: ")
for i in xrange(N):
N = []
a = input('%d. Element: ' %(i+1))
N.append(a)
print N
您重置N
一個空的名單上的for
-loop的每一次迭代,然後在最後一次迭代的最後a
值將被追加到空列表,從而與只有一個項目在N
列表整理。
此外,使用不同的變量名的列表(不是你的輸入N
定義相同的變量)
N = input("Enter the number of elemets: ")
n = [] # use a different variable name for this list
for i in xrange(int(N)): # cast N to integer
a = input('%d. Element: ' %(i+1))
n.append(a) # append to the list `n` not `N`
print n # print the list
運行示例:
Enter the number of elemets: 5
1. Element: 3
2. Element: 4
3. Element: 6
4. Element: 7
5. Element: 8
['3', '4', '6', '7', '8']
你應該** **不一直重置'N'。 –
'N = []'清空'for'循環的每次迭代列表。在進入'for'循環之前移動'N = []'行,並將'N'重命名爲第一行中尚未使用的另一個變量名 – davedwards