假设您想从列表中制作一本词典,以便:
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}
您可以使用
zip
进行以下操作:如果
l = [1,2,3,4,5]
您得到的是输出{1: 2, 2: 3, 3: 4, 4: 5}
编辑: 如果希望输出与第一个示例匹配,可以使用Tim Roberts建议的步骤:
但是,在这个版本中,如果希望最后的元素包含在结果中,您需要自己获取最后的元素,因为这个版本只输出
{1: 2, 3: 4}
(即5
是“丢失的”)相关问题 更多 >
编程相关推荐