将 Python 切片语法传递给函数 [英] Passing Python slice syntax around to functions

查看:31
本文介绍了将 Python 切片语法传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,是否可以准确地封装常见的切片语法并将其传递?我知道我可以使用 slice__slice__ 来模拟切片.但我想传递与 __getitem__ 一起使用的方括号中的完全相同的语法.

In Python, is it possible to encapsulate exactly the common slice syntax and pass it around? I know that I can use slice or __slice__ to emulate slicing. But I want to pass the exact same syntax that I would put in the square brackets that would get used with __getitem__.

例如,假设我编写了一个函数来返回列表的某个部分.

For example, suppose I wrote a function to return some slice of a list.

def get_important_values(some_list, some_condition, slice):
    elems = filter(some_condition, some_list)
    return elems[slice]

如果我手动传入切片对象,这可以正常工作:

This works fine if I manually pass in a slice object:

In [233]: get_important_values([1,2,3,4], lambda x: (x%2) == 0, slice(0, None))
Out[233]: [2, 4]

但我想让用户通过的是完全与他们在 __getitem__ 中使用的切片相同:

But what I want to let the user pass is exactly the same slicing they would have used with __getitem__:

get_important_values([1,2,3,4], lambda x: (x%2) == 0, (0:-1) )

# or

get_important_values([1,2,3,4], lambda x: (x%2) == 0, (0:) )

显然这会产生语法错误.但是有没有什么方法可以让这个工作,而不用为 x:y:t 类型切片编写我自己的迷你解析器,并强制用户将它们作为字符串传递?

Obviously this generates a syntax error. But is there any way to make this work, without writing my own mini parser for the x:y:t type slices, and forcing the user to pass them as strings?

动机

我可以让这个示例函数返回一些直接可切片的内容,例如 filter(some_condition, some_list),它将作为列表的整个结果.但是,在我的实际例子中,内部函数要复杂得多,如果我提前知道用户想要的切片,我可以大大简化计算.但我希望用户不必做太多额外的事情来提前告诉我切片.

I could just make this example function return something directly sliceable, such as filter(some_condition, some_list), which will be the whole result as a list. In my actual example, however, the internal function is much more complicated, and if I know the slice that the user wants ahead of time, I can greatly simplify the calculation. But I want the user to not have to do much extra to tell me the slice ahead of time.

推荐答案

也许以下内容对您有用:

Perhaps something along the following lines would work for you:

class SliceMaker(object):
  def __getitem__(self, item):
    return item

make_slice = SliceMaker()

print make_slice[3]
print make_slice[0:]
print make_slice[:-1]
print make_slice[1:10:2,...]

这个想法是您使用 make_slice[] 而不是手动创建 slice 的实例.通过这样做,您将能够充分利用熟悉的方括号语法.

The idea is that you use make_slice[] instead of manually creating instances of slice. By doing this you'll be able to use the familiar square brackets syntax in all its glory.

这篇关于将 Python 切片语法传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆