有没有更好的方法来获取未知长度列表中的第n个元素?

2024-10-02 10:31:15 发布

您现在位置:Python中文网/ 问答频道 /正文

假设您想从列表中制作一本词典,以便:

l = [1,2,3,4]
d = {1: 2, 3: 4}

以下是我的解决方案:

def autodict(*args):
    container = list(args)
    #                      ↓ especially this
    return {arg: container[container.index(arg) + 1] for arg in args if arg != container[-1]} if len(args) > 1 else set(args)

有没有更好的方法来实现这一点,或者显式for循环在这一点上更好?(这也适用于任何iterable?)

autodict([1,2,3,4,5]) -> {1: 2, 2: 3, 3: 4, 4: 5}
autodict(1) -> {1}
autodict(1,2) -> {1: 2}

Tags: 列表forindexreturnifcontainerdefarg
1条回答
网友
1楼 · 发布于 2024-10-02 10:31:15

您可以使用zip进行以下操作:

dict(zip(l, l[1:]))

如果l = [1,2,3,4,5]您得到的是输出{1: 2, 2: 3, 3: 4, 4: 5}

编辑: 如果希望输出与第一个示例匹配,可以使用Tim Roberts建议的步骤:

dict(zip(l[0::2],l[1::2]))

但是,在这个版本中,如果希望最后的元素包含在结果中,您需要自己获取最后的元素,因为这个版本只输出{1: 2, 3: 4}(即5是“丢失的”)

相关问题 更多 >

    热门问题