我是 Python 編碼的新手,我正在努力解決一個非常簡單的問題。有同樣的問題,但論壇上的 javascript 但它對我沒有幫助。我的代碼是:
def filter_list(l):
for i in l:
if i != str():
l.append(i)
i = i 1
return(l)
print(filter_list([1,2,'a','b']))
If you can help!
謝謝
uj5u.com熱心網友回復:
在我提出解決方案之前,您需要了解一些問題。
字串()
str()創建字串類的新實體。僅當該物件是相同的字串時,將其與物件進行比較==才會成立。
print(1 == str())
>>> False
print("some str" == str())
>>> False
print('' == str())
>>> True
迭代器(無 1)
你有i = i 1你的回圈。這沒有任何意義。i來自回圈遍歷 list 成員的for i in l含義。不能保證你可以加 1。在下一個回圈中將有一個新值ili
l = [1,2,'a']
for i in l:
print(i)
>>> 1
>>> 2
>>> 'a'
要過濾您需要一個新串列
l當您找到一個字串時,您正在追加。這意味著當您的回圈找到一個整數時,它將把它附加到串列的末尾。稍后它將在另一個回圈互動中找到該整數。并再次將其附加到末尾。并在下一次迭代中找到它......永遠。
試試看!自己看看無限回圈。
def filter_list(l):
for i in l:
print(i)
if type(i) != str:
l.append(i)
return(l)
filter_list([1,2,'a','b'])
修復1:修復型別檢查
def filter_list(l):
for i in l:
if type(i) != str:
l.append(i)
return(l)
print(filter_list([1,2,'a','b']))
This infinite loops as discussed above
Fix 2: Create a new output array to push to
def filter_list(l):
output = []
for i in l:
if type(i) != str:
output.append(i)
return output
print(filter_list([1,2,'a','b']))
>>> [1,2]
There we go.
Fix 3: Do it in idiomatic python
Let's use a list comprehension
l = [1,2,'a','b']
output = [x for x in l if type(x) != str]
print(output)
>>> [1, 2]
A list comprehension returns the left most expression x for every element in list l provided the expression on the right (type(x) != str) is true.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435222.html
標籤:python-3.x 列表
上一篇:從兩個嵌套串列制作字典
