交换第一个字典后,从两个列表中创建字典?

时间:2019-04-16 19:00:57

标签: python insert list-comprehension pop

我希望根据一些变量移动列表中整数的位置。为了便于说明,我将数字硬编码到range()和pop()中。

如何将循环结果声明到新列表中-为了以后从键和值列表创建字典。

此代码有效,但我没有新列表:

keys = range(0, 7)
print(keys)
for i in range(1):
     keys.insert(0, keys.pop(1))

print(keys)
In: print(keys)
Out: [0, 1, 2, 3, 4, 5, 6]

In: print(keys)
Out: [6, 0, 1, 2, 3, 4, 5]

此代码不起作用:

keys = range(0, 7)
print(keys)
for i in range(1):
     values = keys.insert(0, keys.pop(1))

print(values)
In: print(keys)
Out: [0, 1, 2, 3, 4, 5, 6]

In: print(values)
Out: None

1 个答案:

答案 0 :(得分:1)

values = range(0, 7)

for i in range(1):
    keys = list(values)
    values.insert(0, values.pop(1))

dictionary = dict(zip(keys, values))

print(keys)
print(values)
print(dictionary)
#[0, 1, 2, 3, 4, 5, 6]
#[1, 0, 2, 3, 4, 5, 6]
#{0: 1, 1: 0, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}
相关问题