在python中为列表添加一个increaseKey

发布于 2024-12-09 09:19:09 字数 453 浏览 1 评论 0 原文

假设一个包含字符串的列表 A 和一个偏移量 x

A=["a","b","c"]
x 是整数
len(A) is int

我需要序列化并返回 json J 这样对于每个 n
J[x+n]=a[n]

我目前使用字典分配,但感觉它们更高效 而不是遍历整个列表。

答案需要是 O(1) 或矛盾。

谢谢。

dict={}

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

assuming a list 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

焚却相思 2024-12-16 09:19:09

如果您确实不想从列表中构造一个 dict,您可以使用依赖于 json 模块的实现细节的 hack:

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)

上面的代码打印

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

因为构造OffsetDict 实例不会迭代列表,这部分的时间复杂度为 O(1)。当然,创建 JSON 输出不可避免地仍然是 O(n)。

该代码依赖于这样一个事实:jsondict 的每个子类视为 dict 并且仅调用 __nonzero__()iteritems() 方法。不要指望该代码非常健壮。更强大的版本需要重新实现 dict 的所有方法。

在 Python 3.x 中,覆盖 items() 而不是 iteritems()

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().

纸伞微斜 2024-12-16 09:19:09

给定以下变量(不要使用 dict/list 作为变量名!):

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

您的示例代码可以编写为:

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

或使用 import itertools as it

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

或(Python 2.6 及更高版本):

d = dict(enumerate(A, offset))

在所有情况下d 现在是 {5: 'a', 6: 'b', 7: 'c'}。比较速度,第一个是最慢的,后两者没有显着差异。

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.

如梦亦如幻 2024-12-16 09:19:09

dict 构造函数可以采用可迭代的键值对来构造字典。因此,您可以:

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

在较新的 Python(2.7 或 3.x)中,有用于 dict 理解的特殊语法:

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

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)}
你另情深 2024-12-16 09:19:09

为什么不在 A 前面添加一个长度为 offset 的列表?

result = [None] * offset + A

Why not prepend a list of length offset to A?

result = [None] * offset + A
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文