gpt4 book ai didi

python - 循环创建字典 D,它看起来像 : {1:100, 2 :99, 3 :98, …,100:1}

转载 作者:太空宇宙 更新时间:2023-11-03 12:26:34 24 4
gpt4 key购买 nike

我需要创建一个字典,结果为 {1:100, 2:99,3:98,...,100:1}

我在胡闹,得到了这个

D = { }
keys = range(101)
i = 0
values = [100]
for i in keys:
for x in values:
x = i
D[x] = i
pass
print D

这有一个输出

{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20, 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31, 32: 32, 33: 33, 34: 34, 35: 35, 36: 36, 37: 37, 38: 38, 39: 39, 40: 40, 41: 41, 42: 42, 43: 43, 44: 44, 45: 45, 46: 46, 47: 47, 48: 48, 49: 49, 50: 50, 51: 51, 52: 52, 53: 53, 54: 54, 55: 55, 56: 56, 57: 57, 58: 58, 59: 59, 60: 60, 61: 61, 62: 62, 63: 63, 64: 64, 65: 65, 66: 66, 67: 67, 68: 68, 69: 69, 70: 70, 71: 71, 72: 72, 73: 73, 74: 74, 75: 75, 76: 76, 77: 77, 78: 78, 79: 79, 80: 80, 81: 81, 82: 82, 83: 83, 84: 84, 85: 85, 86: 86, 87: 87, 88: 88, 89: 89, 90: 90, 91: 91, 92: 92, 93: 93, 94: 94, 95: 95, 96: 96, 97: 97, 98: 98, 99: 99, 100: 100}

所以我需要找到一种方法来反转它并摆脱 0,我知道 .reverse() 不会在字典上工作并且

list(reversed(sorted(a.keys())))

只是让它成为一个列表,去掉了 1:...100:

最佳答案

虽然其他答案是正确的,但我认为这是 dict comprehension 的一个很好的案例.它使代码更易于阅读和更 pythonic

result = { i: 101 - i for i in range(1, 101)}

为了让它变得更好,您可以使用变量使代码可重用,而不是对 101 进行硬编码,因此:

num = 101
result = { i: num - i for i in range(1, num)}

关于python - 循环创建字典 D,它看起来像 : {1:100, 2 :99, 3 :98, …,100:1},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48935409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com