為什么我的代碼不行
def toUppers(L):
??? return [L(x).upper() for x in range(0,len(L) if isinstance(L(x), str)]
print toUppers(['Hello', 'world', 101])
def toUppers(L):
??? return [L(x).upper() for x in range(0,len(L) if isinstance(L(x), str)]
print toUppers(['Hello', 'world', 101])
2016-04-09
舉報
2016-04-10
上面這個就是正確寫法了,
題主的代碼運行的時候直接報了語法錯誤, 首先 if 前面 缺少一個 圓括號結束。所以題主的代碼就成了:
再跑一下,給出了 'list' object is not callable, 仔細一看發現 我們在調用 列表index 時用了 圓括號 L(x),應該是 中括號嘛:
至此,終于調好了 , 但是題主仔細 看一下 你的思路和 標準思路的區別:
不難看出,其實題主的代碼,在每次循環中多查詢了兩次 列表。 相對來說就有些浪費性能了。
最后多說一句,尤其是從其他語言轉過來的人, Python list 的 for...in..., 不要太好用。
2016-04-09
不可以打印,L中可能包含非字符串,要分開
2016-04-09
? return [x.upper() for x in L if isinstance(x, str)]