Ev.*_*nis 1 python dictionary python-3.x
我需要编写一个函数,将'map'-1映射到' - ',1映射到''(是的,没有),其他所有值都写入自身的字符串表示.而不是使用if语句我虽然我会用这样的字典这样做:
def adj(my_value):
return {-1: '-', 1: '', my_value: str(my_value)}[my_value]
Run Code Online (Sandbox Code Playgroud)
然后它打了我,这个字典允许重复键,行为如下:
for x in [-1, 1, 4]:
print(adj(x))
# -> -1
# -> 1
# -> 4
Run Code Online (Sandbox Code Playgroud)
我确实运行了多次,以确保print()不是"随机",因为dicts没有排序,但我一直得到这个输出.
现在这绝对不是我想要的行为,并且绝不可以信任这样的构造但是有人知道为什么甚至允许这样的事情,因为重复的密钥不是吗?如何进行计算?
您制作的词典没有重复的键."重复"相互覆盖.这就好像你这样做了:
d = {}
d[1] = ''
d[1] = 1
print(d[1])
Run Code Online (Sandbox Code Playgroud)
展示:
>>> 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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你可以写这样的函数:
def adj(my_value)
d = {-1: '-', 1: ''}
return d.get(my_value, str(my_value))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51 次 |
| 最近记录: |