以下代码块提出了上述问题:
L1 = [1, True, 0, False]*5
L2 = [True, 1, False, 0]*5
D1 = dict(zip(L1, range(len(L1))))
D2 = dict(zip(L2, range(len(L2))))
print(L1) # [1, True, 0, False, 1, True, 0, False, 1, True, 0, False, 1, True, 0, False, 1, True, 0, False]
print(D1) # {1: 17, 0: 19}
print(L2) # [True, 1, False, 0, True, 1, False, 0, True, 1, False, 0, True, 1, False, 0, True, 1, False, 0]
print(D2) # {True: 17, False: 19}
#print(True in D1)
#print(0 in D2)
#print(True == 1)
#print(False == 0)
我可以理解,作为int
的子类,这是bool
的预期行为。但这不影响list
的结构吗?
在任何情况下,我如何处理它们(1 and 0
或True and False
(的显式存在?即,我想要像{1 : 16, True : 17, 0 : 18, False : 19}
(在D1
的情况下(这样的东西,以一种纯粹的蟒蛇的方式。
从评论中收集想法*以获得答案:
你似乎意识到了这一点,但发生这种情况的原因是因为True == 1
和False == 0
。这意味着,作为dict键,它们将被映射为相等的,并且不可能有重复的键。
克服这一点:
-
您可以将密钥转换为字符串:
L1 = [1, True, 0, False]*5 D1 = dict(zip(map(str, L1), range(len(L1)))) print(D1)
将给出:
{'1': 16, 'True': 17, '0': 18, 'False': 19}
但这样做的缺点是无法真正说出密钥的类型。你可以在阅读dict:时使用
ast.literal_eval
来克服这个问题import ast for key, value in D1.items(): key = ast.literal_eval(key) print(key, type(key))
将给出:
1 <class 'int'> True <class 'bool'> 0 <class 'int'> False <class 'bool'>
将dict的键更改为值及其类型的元组:
L1 = [1, True, 0, False]*5
D1 = dict(zip(zip(L1, [type(x) for x in L1]), range(len(L1))))
print(D1)
将给出:
{(1, <class 'int'>): 16, (True, <class 'bool'>): 17, (0, <class 'int'>): 18, (False, <class 'bool'>): 19}
当读取dict时,您可以获得键的0-index元素,以获得实际的实际值。
*通过CozyCode转换为字符串思想。通过VPfB将类型添加到关键思想中