MST
星途 面试题库

面试题:Python动态生成列表的索引错误防范

假设你正在开发一个程序,该程序会根据用户输入动态生成一个列表,例如用户输入数字`n`,程序生成列表`[i for i in range(n)]`。然后程序中有多个函数会基于用户输入的索引对这个列表进行操作。请设计一套完整的机制,不仅要防止常规的索引错误,还要考虑在多线程环境下可能由于列表动态变化导致的索引失效问题,并编写相应的代码示例。阐述你设计的机制如何保证索引操作的正确性和稳定性。
45.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

机制设计

  1. 常规索引错误处理:在进行索引操作前,检查索引值是否在合法范围内。
  2. 多线程环境下索引失效处理:使用锁(Lock)来保证在对列表进行操作时,其他线程无法修改列表,避免索引失效。

代码示例

import threading


class SafeList:
    def __init__(self):
        self.lock = threading.Lock()
        self.data = []

    def generate_list(self, n):
        with self.lock:
            self.data = [i for i in range(n)]

    def get_item(self, index):
        with self.lock:
            if 0 <= index < len(self.data):
                return self.data[index]
            else:
                raise IndexError("Index out of range")

    def set_item(self, index, value):
        with self.lock:
            if 0 <= index < len(self.data):
                self.data[index] = value
            else:
                raise IndexError("Index out of range")


def worker(safe_list, index, value):
    try:
        safe_list.set_item(index, value)
        result = safe_list.get_item(index)
        print(f"Thread {threading.current_thread().name} set and got: {result}")
    except IndexError as e:
        print(f"Thread {threading.current_thread().name} error: {e}")


if __name__ == "__main__":
    safe_list = SafeList()
    safe_list.generate_list(5)

    threads = []
    for i in range(3):
        t = threading.Thread(target=worker, args=(safe_list, i, i * 10))
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

机制说明

  1. SafeList:封装了列表操作,并使用threading.Lock来保证线程安全。
  2. generate_list方法:在生成列表时加锁,防止其他线程在生成过程中访问列表。
  3. get_itemset_item方法:在进行索引操作前,先检查索引是否合法,并且加锁防止列表在操作过程中被其他线程修改,从而保证索引操作的正确性和稳定性。