面试题答案
一键面试实现思路
- 数据结构分析:对于嵌套字典和列表的复杂数据结构,需要通过索引和键来定位特定层级的字典值。
- 动态访问:可以编写一个递归函数来根据层级动态访问字典值。
- 多线程安全:使用锁机制(如
threading.Lock
)来确保在多线程环境下对字典值的访问是安全的,避免数据竞争。
代码示例
import threading
def get_nested_value(data, keys):
value = data
for key in keys:
if isinstance(value, list):
key = int(key)
if isinstance(value, dict) and key in value:
value = value[key]
else:
raise KeyError(key)
return value
class SafeNestedDict:
def __init__(self, initial_data=None):
self.data = initial_data if initial_data else {}
self.lock = threading.Lock()
def get_value(self, keys):
with self.lock:
return get_nested_value(self.data, keys)
# 示例使用
if __name__ == "__main__":
data = {
"a": {
"b": [1, 2, 3],
"c": {
"d": "target value"
}
}
}
safe_dict = SafeNestedDict(data)
def access_thread(keys):
try:
value = safe_dict.get_value(keys)
print(f"Thread {threading.current_thread().name} got value: {value}")
except KeyError as e:
print(f"Thread {threading.current_thread().name} got KeyError: {e}")
threads = []
keys_list = [["a", "b", 1], ["a", "c", "d"]]
for keys in keys_list:
t = threading.Thread(target=access_thread, args=(keys,))
threads.append(t)
t.start()
for t in threads:
t.join()
在上述代码中:
get_nested_value
函数负责递归地从嵌套数据结构中获取值。SafeNestedDict
类封装了数据结构,并使用threading.Lock
来确保多线程环境下的安全访问。access_thread
函数模拟不同线程对数据的访问,通过SafeNestedDict
的get_value
方法获取特定层级的字典值。