设计并实现一个数组类,要求能够把包含数字的列表、元组或 range 对象转换为数组, 并能够修改数组中指定位置上的元素值。
时间: 2024-12-13 08:26:08 浏览: 2
设计一个数组类,可以处理不同类型的数据源如列表、元组和range,并支持元素的修改操作,我们可以这样做:
```python
class ArrayAdapter:
def __init__(self, data):
if isinstance(data, list) or isinstance(data, tuple):
self.array = list(data)
elif isinstance(data, range):
self.array = [i for i in data]
else:
raise ValueError("Unsupported data type. Only lists, tuples and ranges are accepted.")
def convert_to_array(self):
return self.array
def set_element(self, index, value):
if index >= len(self.array):
raise IndexError("Index out of range.")
self.array[index] = value
def get_element(self, index):
if index < 0 or index >= len(self.array):
raise IndexError("Index out of range.")
return self.array[index]
# 示例使用
data_list = [1, 2, 3]
adapter = ArrayAdapter(data_list)
print(adapter.convert_to_array()) # 输出: [1, 2, 3]
adapter.set_element(1, "two")
print(adapter.get_element(1)) # 输出: 'two'
range_data = range(4, 8)
adapter = ArrayAdapter(range_data)
print(adapter.convert_to_array()) # 输出: [4, 5, 6, 7]
```
阅读全文