python-カスタムリストクラス
21067 ワード
class MyList:
def __init__(self,data = None):
self.data = None
if data is None:
self.data = []
else:
self.data = data
#
def append(self,value):
item = [value]
self.data = self.data +item
#
def clear(self):
del self.data
self.data = []
return self.data
#
def insert(self,index,value):
len_list = len(self.data)
for i in range(3,len_list):
value, self.data[i] = self.data[i], value
self.data.append(value)
return self.data
# ,
def pop(self,index = -1):
print(self.data[index])
del self.data[index]
return self.data
#
def extend(self,item):
self.data = self.data +item # + ,
return self.data
#
def remove(self,value):
for index in self.data:
if value == self.data[index]:
del self.data[index]
break
#
def index(self,value):
for i in self.data:
if value == self.data[i]:
print(i)
break
# ,
def sort(self):
n = len(self.data)
for i in range(n):
for j in range(0,n-i-1):
if self.data[j] > self.data[j+1]:
self.data[j],self.data[j+1] = self.data[j+1],self.data[j]
return self.data
#
def reverse(self):
self.data = self.data[::-1] #
return self.data
# i,j = 0,len(self.data)-1 #
# while (i
# self.data[i],self.data[j] = self.data[j],self.data[i]
# i += 1
# j -= 1
# return self.data
#
def count(self,coun):
count = 0
for i in range(len(self.data)):
if self.data[i] == coun:
count = count + 1
print(count)
return self.data
#
def copy(self):
item = self.data[:]
return item
#
def is_empty(self):
if len(self.data) == 0:
return True
return False
#
def __str__(self):
return str(self.data)
a = MyList([9, 2, 8, 7, 5, 4, 3, 2, 1, 2, 3])
a.append(10)
print(a)
a.append(100)
print(a)
# [9, 2, 8, 7, 5, 4, 3, 2, 1, 2, 3, 10]
# [9, 2, 8, 7, 5, 4, 3, 2, 1, 2, 3, 10, 100]
a.clear()
print(a)
# []
a.insert(3,10)
print(a)
# [9, 2, 8, 10, 7, 5, 4, 3, 2, 1, 2, 3]
a.pop()
# 3
print(a)
# [9, 2, 8, 7, 5, 4, 3, 2, 1, 2]
a.pop(4)
print(a)
# 5
# [9, 2, 8, 7, 4, 3, 2, 1, 2]
a.extend([1,2,3])
print(a)
# [9, 2, 8, 7, 5, 4, 3, 2, 1, 2, 3, 1, 2, 3]
a.remove(8)
print(a)
# [9, 2, 7, 5, 4, 3, 2, 1, 2, 3]
a.index(1)
# 8
a.sort()
print(a)
# [1, 2, 2, 2, 3, 3, 4, 5, 7, 8, 9]
a.reverse()
print(a)
# [3, 2, 1, 2, 3, 4, 5, 7, 8, 2, 9]
a.count(2)
# 3
b = a.copy()
print(b)
# [9, 2, 8, 7, 5, 4, 3, 2, 1, 2, 3]
b = a.is_empty()
print(b)
# False