![](/img/trans.png)
[英]How to change the index of an element in a list/array to another position/index without deleting/changing the original element and its value
[英]Reference position of index without value
從 Python 3 開始,您可以按類型顯式聲明變量:
x: int = 3
or:
def f(x: int):
return x
我將如何使用索引號執行此操作?
我試圖在不直接計算值的情況下維護值的地址......
這是你想要的嗎?
x = [3]
a= x.index(3)
print (a)
輸出 0
int
實際上不是必需的,而or
是為了什么?
當您分配不正確的值類型時,類型提示不會引發異常。 它是目前唯一已知的文檔。 請參閱此問題: https://stackoverflow.com/a/44282299/8170215
不過,如果你想為字典定義類型提示,你可以這樣做:
from typing import Dict
x: Dict[int, str] = {1: 'a', 2: 'b'}
當您分配諸如x = 'some string'
或x['a'] = 'b'
類的內容時,它不會引發異常
如果您希望 python 引發 AssertionError,您可以使用:
# No exception
x = {1: 'a', 2: 'b'}
assert all(isinstance(key, int) for key in x)
# AssertionError
x = {'a': 'a', 2: 'b'}
assert all(isinstance(key, int) for key in x)
或者,您可以使用像pydantic這樣的庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.