我需要编写一个函数,将 -1“映射”为“-”,将 1 映射为“”(是的,什么都没有),并将所有其他值“映射”为自身的字符串表示形式。我不使用 if 语句,而是使用像这样的字典:
def adj(my_value):
return {-1: '-', 1: '', my_value: str(my_value)}[my_value]
然后它打动了我,这个字典允许重复的键并且表现如下:
for x in [-1, 1, 4]:
print(adj(x))
# -> -1
# -> 1
# -> 4
我确实多次运行它以确保 print() 不是“随机的”,因为字典没有排序,但我始终得到这个输出。
现在这绝对不是我想要的行为,这样的结构绝对不能被信任,但是有谁知道为什么这样的事情甚至被允许,因为重复的 key 是不允许的?计算是如何进行的?
请您参考如下方法:
您制作的字典没有重复键。 “重复项”相互覆盖。就好像你这样做了一样:
d = {}
d[1] = ''
d[1] = 1
print(d[1])
演示:
>>> def adj(my_value):
... d = {-1: '-', 1: '', my_value: str(my_value)}
... print(d)
... return d[my_value]
...
>>> for x in [-1, 1, 4]:
... print(adj(x))
...
{1: '', -1: '-1'}
-1
{1: '1', -1: '-'}
1
{1: '', 4: '4', -1: '-'}
4
顺便说一句,你可以这样写函数:
def adj(my_value)
d = {-1: '-', 1: ''}
return d.get(my_value, str(my_value))
