开发者

make a increaseKey for list in python

assuming a lis开发者_如何学Ct A with strings, and an offset x.

A=["a","b","c"]

x is int

len(A) is int

I need to serialize and return json J such that for each n<len(A)

J[x+n]=a[n]

I currently use dict assigning, but It feels like their is something more efficient instead of going over the entire list.

answer needs to be O(1) or a contradiction.

Thanks.

dict={}

for i,x in enumerate(List):
    dict[i+offset]=x


If you really don't want to construct a dict from your list, you can use a hack that depends on implementation details of the json module:

class OffsetDict(dict):
    def __init__(self, lst, offset):
        self.lst = lst
        self.offset = offset
    def __nonzero__(self):
        return bool(self.lst)
    def iteritems(self):
        return enumerate(self.lst, self.offset)

A = ["a", "b", "c"]
d = OffsetDict(A, 5)
print json.dumps(d)

The above code prints

{"5": "a", "6": "b", "7": "c"}

Because constructing an OffsetDict instance does not iterate the list, this part would be O(1). Creating the JSON output inevitably remains O(n) of course.

The code relies on the fact that json treats every subclass of dict as a dict and only calls the __nonzero__() and iteritems() methods. Don't expect that code to be very robust. A more robust version would need to reimplement all of dict's methods.

In Python 3.x, overwrite items() instead of iteritems().


Given following variables (don't use dict/list as variable names!):

offset = 5
A = ["a","b","c"]

Your example code can be written as:

d = dict(zip(range(offset, offset+len(A)), A))

or using import itertools as it:

d = dict(it.izip(it.count(offset), A))

or (Python 2.6 and newer):

d = dict(enumerate(A, offset))

In all cases d is now {5: 'a', 6: 'b', 7: 'c'}. Comparing the speeds, the first is the slowest and there is no significant difference between the latter two.


The dict constructor can take an iterable of key-value pairs to construct the dict. So, you can have:

some_dictionary = dict((i + offset, x) for i, x in enumerate(some_list))

In newer Pythons (2.7 or 3.x), there's special syntax for dict comprehension:

some_dictionary = {i + offset: x for i, x in enumerate(some_list)}


Why not prepend a list of length offset to A?

result = [None] * offset + A
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜