簡體   English   中英

map 兩個不同的字符串作為一個字符串的最pythonic方法是什么?

[英]What is the most pythonic way to map two different strings, to act as one?

問題

想象一下兩個服務正在運行:

服務 1 有兩種狀態: ACTIVE/INACTIVE

服務 2 有兩種狀態: RUNNING/TERMINATED

我們想做一個簡單的狀態比較:

service1_status = get_service2_status()
service2_status = get_service2_status()

if service1_status == service2_status:
   // They match!
else:
   // They don't match!

一個有效的解決方案

這當然是一個相對簡單的任務。 一個可行的解決方案是這樣的:

service1_status = get_service2_status()
service2_status = get_service2_status()

if service1_status == 'ACTIVE' and service2_status == 'RUNNING':
   return "They match!"
elif service1_status == 'INACTIVE' and service2_status == 'TERMINATED':
   return "They match!"
else:
   return "They don't match!"

問題 - 但更困難

現在想象一下這個例子,每個服務有一百個不同的狀態,而不是兩個。

if 語句將是壓倒性的。 我正在尋找一種更優雅的編程方式。 例如:

matching_tuples = [('x1', 'y1'), ('x2', 'y2'), ..., ('x100', 'y100')]

service1_status = get_service2_status()
service2_status = get_service2_status()

if (service1_status, service2_status) in matching_tuples:
   return "They match!"
elif:
   return "They don't match!"

這有效並且很好。 我想知道是否有更好、更 Pythonic 和優雅的方式將兩個字符串結合在一起並進行比較。

確定一個基線服務和 map 其對另一個的狀態:

service1_status = get_service2_status()
service2_status = get_service2_status()

mapping = {"ACTIVE": "RUNNING", "INACTIVE": "TERMINATED"}

if mapping[service1_status] == service2_status:
   return "They match!"
else:
   return "They don't match!"

如果可能未映射 service1 的狀態,您可以選擇:

  1. 提高KeyError (如上,使用mapping[service1_status] )。

  2. 通過使用mapping.get(service1_status)來消除錯誤並將其視為“不匹配”。

  3. 捕獲錯誤並將其作為信息調試消息重新引發:

     try: match = mapping[service1_status] == service2_status except KeyError: raise KeyError(f"The status {service1_status} of service1 is not mapped to any status in service2")

根據您的實際輸入,您可能不需要手動構建字典:

  • 如果您已經有類似您提供的matching_tuples的東西,您可以將其直接傳遞給 dict 構造函數 - mapping = dict(matching_tuples)

  • 如果你有兩個匹配的狀態列表,你可以做mapping = dict(zip(statuses1, statuses2)) (注意基本上matching_tuples = list(zip(statuses1, statuses2))

我還必須從后端和前端獲取 map 密鑰。
對於映射,我通常使用dictionary ,您可以像這樣添加任意數量的鍵。

MapService1to2 = {
    "ACTIVE": "RUNNING",
    "INACTIVE": "TERMINATED"
}

service1_status = get_service2_status()
service2_status = get_service2_status()

if MapService1to2[service1_status] == service2_status:
    print("They match")
else:
    print("They don't match")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM