[英]Python: How to For Loop a list and append to new list
練習我的python。
任務:遍歷列表A並創建一個新列表,僅包含列表A中介於0-5之間的項目。
我在這里做錯了什么
a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]
def new_list(x):
for item in range(len(x)):
new = []
if x[item] < 5 and x[item] > 0:
(new.append(item))
return new
print(new_list(a))
我只是得到[1]
的答案。
您的返回命令位於循環內部,因此,在遇到第一種情況時,它將立即返回退出函數的值。
這是您的代碼外觀的示例
a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]
def new_list(x):
new = []
for item in range(len(x)):
if x[item] < 5 and x[item] > 0:
new.append(x[item])
return new
print new_list(a)
您可以通過使用列表理解來獲得相同的結果
def new_list(x):
return [item for item in x if 0 < item < 5]
您每次通過循環都會將new
重置為一個全新的空列表,這會丟棄先前迭代中完成的所有工作。
另外,在if
語句中,您正在調用return
,它會立即退出函數,因此您永遠不會處理列表的其余部分。
您可能想要這樣的東西:
def new_list(x):
new = []
for item in x:
if 0 < item < 5:
new.append(item)
return new
只是我的建議。 您可以在此處使用filter()而不是進行自己的循環。
a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]
def new_list(x, low=0, high=5):
return filter(lambda f: f in range(low, high), x)
篩選器會返回一個新列表,其中的元素將傳遞給定謂詞,它等效於
[item for item in iterable if function(item)]
根據文檔。
因此
print new_list(a)
結果是:
[1, 2, 3, 5]
這樣,您可以檢查任何值,例如:
print new_list(a, 5, 10)
[5, 8]
三個錯誤:
for
循環的每次迭代中重新實例化new
。 return new
。 item
,但這是您的索引。 在您的代碼中,您將不得不附加x[item]
。 帶有更正的代碼:
a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]
def new_list(x):
new = []
for item in range(len(x)):
if x[item] < 5 and x[item] > 0:
new.append(x[item])
return new
print(new_list(a))
輸出:
[1, 2, 3]
意見建議:
x
直接( for item in x: ...
)。 0 < item < 5
。 編寫所有三個建議的代碼:
>>> [item for item in a if 0 < item < 5]
>>> [1, 2, 3]
只是一個建議!
空列表位於For循環內部, 這意味着每次迭代都會創建一個新的空列表
'return'也在for循環內,它不理想,您希望在循環用完並附加所有合適的元素后返回它。
a = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98] def new_list(x): new = [] for item in range(len(x)): if x[item] < 5 and x[item] > 0: new.append(item) return new print(new_list(a))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.