Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在列表理解中使用python类型_Python_If Statement_List Comprehension - Fatal编程技术网

如何在列表理解中使用python类型

如何在列表理解中使用python类型,python,if-statement,list-comprehension,Python,If Statement,List Comprehension,如何在列表理解中使用python类型?? 我可以吗 >>ll [1,2,5,'foo','baz','wert'] >>>[x代表ll中的x] [1,2,5,'foo','baz','wert'] >>>[x表示ll中的x,如果类型(x)='int'] [] >>>[x*20.0表示ll中的x,如果类型(x)='int'] [] >>>类型(ll[0]) 寻找:[20,40,100,'foo','baz','wert']你通常不会。改为使用。您应该使用“is int”而不是“='int” [2

如何在列表理解中使用python类型?? 我可以吗

>>ll
[1,2,5,'foo','baz','wert']
>>>[x代表ll中的x]
[1,2,5,'foo','baz','wert']
>>>[x表示ll中的x,如果类型(x)='int']
[]
>>>[x*20.0表示ll中的x,如果类型(x)='int']
[]
>>>类型(ll[0])
寻找:
[20,40,100,'foo','baz','wert']

你通常不会。改为使用。

您应该使用“is int”而不是“='int”


[20*x如果类型(x)是int,那么ll中x的类型是x]

通常,在Python中,最佳实践是使用“Duck Typing”。一种方法是使用异常处理,在这种情况下需要一个助手函数:

def safe_multiply(x, y):
    try:
        return x * y
    except TypeError:
        return x

[safe_multiply(x, 20) for x in ll]
另一个答案是查看对象是否有乘法方法:

[x * 20 if hasattr(x, "__mul__") else x for x in ll]
但上述两种方法都有一个怪癖:在Python中,将
*
与字符串一起使用是合法的,结果会重复字符串:

print("foo" * 3)  # prints "foofoofoo"
所以最好的办法是使用伊格纳西奥·巴斯克斯·艾布拉姆斯的答案。他实际上没有给你密码,所以这里是:

[x * 20 if isinstance(x, int) else x for x in ll]
不要使用==,使用“是” 您需要这样编写代码:

[x for x in ll if type(x) is 'int']
试试看:

In [6]: [x * 20.0 if type(x) is int else x for x in ll]
Out[6]: [20.0, 40.0, 100.0, 'foo', 'baz', 'wert']

在这里,您正在使用
检查type(x)是否为int
,如果是这样-乘法,则只需将x添加到结果列表中(
否则x
),完全按照您的需要。

'int'
只是一个字符串。您需要
int
(不带引号)
isinstance
通常比使用
type
type(1)是“type”类型,而不是“string”类型,type(type(1))==type如何使用,我在想如果要获得正确的输出,为什么要使用
else
?你的原稿没有。啊哈,我现在明白你的目的了。相应地修改了我的答案。如果你看问题的底部,这里有一个期望输出的示例。字符串应该原封不动地传递,而不是过滤掉。现在是否更好?对不起,我是新手。
>>> ll = [1, 2, 5, 'foo', 'baz', 'wert']
>>> [ x*20.0 if isinstance(x, int) else x for x in ll]
[20.0, 40.0, 100.0, 'foo', 'baz', 'wert']
In [6]: [x * 20.0 if type(x) is int else x for x in ll]
Out[6]: [20.0, 40.0, 100.0, 'foo', 'baz', 'wert']