开发者

Is it possible to refer to the current list's length from inside the index?

I'd like to say something like: [1, 2, 3, 4][len/2] where len refers to the length of this unnamed list.

Is there a way开发者_StackOverflow to do this in python?


To answer your question, you cannot do this without having the list exist beforehand. However you can simply do:

>>> l = [1,2,3,4]
>>> l[len(l)/2]
3


I don't think that something like that is possible out of the box. But the more pythonic way is anyway to make your idea more explizit. Why not write it like this:

def middle(*items):
    return items[len(items)/2]

print middle(1,2,3,4)


just for fun

def half(a):
    return len(a) / 2 

class _(object):
    def __init__(self, *args):
        self.l = list(args)
    def __getitem__(self, idx):
        if type(idx) == int:
            return self.l[idx]
        else:
            return self.l[idx(self.l)]

print _(1, 2, 3, 4)[half]

Though @Mike Lewis' answer won.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜