[英]is there some kind of expression evaluation within list/tuple slicing syntax within Python?
with numpy arrays, you can use some kind of inequality within the square bracket slicing syntax: 使用numpy数组,您可以在方括号切片语法中使用某种不等式:
>>>arr = numpy.array([1,2,3])
>>>arr[arr>=2]
array([2, 3])
is there some kind of equivalent syntax within regular python data structures? 常规python数据结构中是否存在某种等价语法? I expected to get an error when I tried: 我尝试时遇到错误:
>>>lis = [1,2,3]
>>>lis[lis > 2]
2
but instead of an exception of some type, I get a returned value of 2, which doesn't make a lot of sense. 但不是某种类型的异常,我得到的返回值为2,这没有多大意义。
ps I couldn't find the documentation for this syntax at all, so if someone could point me to it for numpy and for regular python(if it exists) that would be great. ps我根本找不到这个语法的文档,所以如果有人能指出我的numpy和常规python(如果它存在)那将是伟大的。
In Python 2.x lis > 2
returns True
. 在Python 2.x中, lis > 2
返回True
。 This is because the operands have different types and there is no comparison operator defined for those two types, so it compares the class names in alphabetical order ( "list" > "int"
). 这是因为操作数具有不同的类型,并且没有为这两种类型定义比较运算符,因此它按字母顺序比较类名( "list" > "int"
)。 Since True
is the same as 1
, you get the item at index 1. 由于True
与1
相同,因此您将获得索引1处的项目。
In Python 3.x this expression would give you an error (a much less surprising result). 在Python 3.x中,这个表达式会给你一个错误(一个不那么令人惊讶的结果)。
TypeError: unorderable types: list() > int()
To do what you want you should use a list comprehension: 要做你想做的事,你应该使用列表理解:
[x for x in lis if x > 2]
使用列表理解:
[a for a in lis if a>=2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.