[英](Python) I am having trouble Finding the integer values form [“a”, 1 , 4 ,6 ,”b” , “d” ,7 , “o”] list using list comprehension method
Here is the following code that I have executed but the answer I desired should be like [1, 4, 6, 7] but instead the output is [False, True, True, True, False, False, True, False]... Please guide me on how can I get the desired output.这是我执行的以下代码,但我想要的答案应该是 [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]
means: fill the list with the values of (type(x) == int)
(which are booleans), where the elements x
come from a_list
. [(type(x) == int) for x in a_list]
表示:用(type(x) == int)
的值(布尔值)填充列表,其中元素x
来自a_list
。 Thus, this list comprehension creates a list of booleans.因此,这个列表推导创建了一个布尔值列表。
You want to get all the items of a_list
that satisfy some criterion.您想获取满足某些条件的
a_list
的所有项目。 So, use this:所以,使用这个:
[
x # get all items of `a_list`...
for x in a_list
if isinstance(x, int) # ...that satisfy this
]
Here's why you should use isinstance(x, int)
instead of type(x) == int
: What are the differences between type() and isinstance()?这就是为什么你应该使用
isinstance(x, int)
而不是type(x) == int
: type() 和 isinstance() 之间有什么区别? . .
you did well, the reason why print(result_list) returns boolean values is because its returning the result of the comparison done in type (x) == int.你做得很好, print(result_list) 返回 boolean 值的原因是因为它返回类型 (x) == int 中完成的比较结果。
In order to return the int values in the list, you need to say for x where x is the value in a_list, if its of type int, store that value in a new list.为了返回列表中的 int 值,您需要说明 x 其中 x 是 a_list 中的值,如果它的类型为 int,则将该值存储在新列表中。 I named the result list for integers result_num_list See code snippet below:
我将结果列表命名为整数 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)
The output will be [1, 4, 6, 7] output 将是 [1, 4, 6, 7]
There is a long way of doing this and a short way: Short:这样做有很长的路要走,也有很短的路: 短:
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)
Long (but easier to read):长(但更容易阅读):
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.