2 回答

TA貢獻1796條經驗 獲得超4個贊
類型注釋應該是Tuple[t1, t2, ...]
對應t1, t2...
元組值的類型。您輸入的方式暗示了您的元組,這意味著它是一個包含單個字符串項的元組。
創建類型提示系統是為了給 python 帶來類似靜態的聲明,所以有兩點需要注意
Tuple[number, number]
如果您有 2-3 個項目的元組(例如,表示 2D 點),則注釋元組是有意義的。您擁有的是一個集合,最好將其注釋為Iterable[str]
.沒有辦法表示一個集合是排序的,因為類型注釋只注釋type,這與集合是否排序無關。

TA貢獻1828條經驗 獲得超4個贊
您不能說元組可以使用類型提示進行二進制搜索。但是,您可以編寫一個裝飾器來包裝您的函數,強制所有輸入元組進行排序。如果您有許多需要排序元組作為輸入的函數,這可能是一個好主意。它不會修改元組(它不能——元組不可變)
def is_sorted(t):
""" Returns true if the tuple, t, is sorted """
return sorted(list(t)) == list(t)
def enforce_sort(func):
def inner(*args, **kwargs):
new_args = [None]*len(args) # Since args is a tuple, we can't modify it
for n, arg in enumerate(args):
new_args[n] = arg
if isinstance(arg, tuple):
## Do you want to sort it?
new_args[n] = tuple(sorted(arg))
## Or do you wait to raise an exception if its not sorted?
# if not is_sorted(arg):
# raise ValueError("Input tuple must be sorted")
for k, v in kwargs.items():
if isinstance(v, tuple):
## Do you want to sort it?
kwargs[k] = tuple(sorted(v))
## Or do you want to raise an exception if its not sorted?
# if not is_sorted(v):
# raise ValueError("Input tuple must be sorted")
return func(*new_args, **kwargs)
return inner
@enforce_sort
def show_twoples(t1, t2):
""" prints two tuples, t1 and t2 """
print(f"t1: {t1}")
print(f"t2: {t2}")
a = (1,2,3,4,5) # Sorted
b = (9,8,6,4,2) # Not sorted
c = [1,2,6,2,3] # Not sorted, but not a tuple so it won't be affected
print(f"\nOriginal: t1 = {a}, t2 = ")
show_twoples(a, b)
print(f"\nOriginal: t1 = , t2 = {a}")
show_twoples(b, a)
print(f"\nOriginal: t1 = {a} t2 = {c}")
show_twoples(a, c)
print(f"\nOriginal: t1 = {c}, t2 = ")
show_twoples(t1 = c, t2 = b)
輸出:
Original: t1 = (1, 2, 3, 4, 5), t2 = (9, 8, 6, 4, 2)
t1: (1, 2, 3, 4, 5)
t2: (2, 4, 6, 8, 9)
Original: t1 = (9, 8, 6, 4, 2), t2 = (1, 2, 3, 4, 5)
t1: (2, 4, 6, 8, 9)
t2: (1, 2, 3, 4, 5)
Original: t1 = (1, 2, 3, 4, 5) t2 = [1, 2, 6, 2, 3]
t1: (1, 2, 3, 4, 5)
t2: [1, 2, 6, 2, 3]
Original: t1 = [1, 2, 6, 2, 3], t2 = (9, 8, 6, 4, 2)
t1: [1, 2, 6, 2, 3]
t2: (2, 4, 6, 8, 9)
根據您的需要,您可以在裝飾器中自動對元組進行排序(這就是它現在正在做的事情),或者如果元組未排序(通過切換注釋掉的部分),您可以引發異常。
添加回答
舉報