[英](Python) I am having trouble Finding the integer values form [“a”, 1 , 4 ,6 ,”b” , “d” ,7 , “o”] list using list comprehension method
這是我執行的以下代碼,但我想要的答案應該是 [1, 4, 6, 7] 但 output 是 [False, True, True, True, False, False, True, False].. . 請指導我如何獲得所需的 output。
a_list = ["a", 1, 4, 6, "b", "d", 7, "o"]
result_list = [(type(x) == int) for x in a_list]
print(result_list)
[(type(x) == int) for x in a_list]
表示:用(type(x) == int)
的值(布爾值)填充列表,其中元素x
來自a_list
。 因此,這個列表推導創建了一個布爾值列表。
您想獲取滿足某些條件的a_list
的所有項目。 所以,使用這個:
[
x # get all items of `a_list`...
for x in a_list
if isinstance(x, int) # ...that satisfy this
]
這就是為什么你應該使用isinstance(x, int)
而不是type(x) == int
: type() 和 isinstance() 之間有什么區別? .
你做得很好, print(result_list) 返回 boolean 值的原因是因為它返回類型 (x) == int 中完成的比較結果。
為了返回列表中的 int 值,您需要說明 x 其中 x 是 a_list 中的值,如果它的類型為 int,則將該值存儲在新列表中。 我將結果列表命名為整數 result_num_list 請參見下面的代碼片段:
a_list = ["a", 1, 4, 6, "b", "d", 7, "o"]
result_num_list = [x for x in a_list if type(x)==int]
print(result_num_list)
output 將是 [1, 4, 6, 7]
這樣做有很長的路要走,也有很短的路: 短:
a_list = ["a", 1, 4, 6, "b", "d", 7, "o"]
result_list = [x for x in a_list if (type(x) == int)]
print(result_list)
長(但更容易閱讀):
a_list = ["a", 1, 4, 6, "b", "d", 7, "o"]
result_list = []
for i in a_list:
if type(i) == int:
result_list.append(i)
print(result_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.