Python中有没有办法将数组添加到下一个可用空间?因此,如果 (0,0) 已经有一个值,请转到 (0,1) 并在那里添加值。我走到了下面,我现在被困住了..
class Array:
def __init__(self):
self.array = [[0 for x in range(5)] for x in range(5)]
def view(self):
for x in self.array:
print(x)
def input(self):
item = input("Enter an item: ")
self.array[0][0] = item
array = Array()
array.input()
array.view()
这里有一个例子。我只是运行循环 9 次。您应该能够将其处理到您的 OOP 样式代码中。我也在使用标准库中的 pprint 模块,因为我喜欢它显示嵌套列表的方式。
from pprint import pprint as pp
myList = [[0 for x in range(5)] for x in range(5)]
for i in range(9):
userInput = int(input("Enter an item: "))
isFound = False # This flag is used to prevent duplicate entries.
for rowIndex, row in enumerate(myList):
for colIndex, column in enumerate(row):
if column == 0 and not isFound:
myList[rowIndex][colIndex] = userInput
isFound = True
break
pp(myList)
循环最后一次迭代后的输出:(假设始终输入 5):
Enter an item: 5
[[5, 5, 5, 5, 5],
[5, 5, 5, 5, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
class Array:
def __init__(self):
self.myList = [[0 for x in range(5)] for x in range(5)]
def input(self):
print("You will be asked to put a value, if you want to stop, press RETURN key.")
for i in range(25):
print()
userInput = input("Enter an item: ")
isFound = False
if userInput == '':
menu()
for rowIndex, row in enumerate(self.myList):
for colIndex, column in enumerate(row):
if column == 0 and not isFound:
self.myList[rowIndex][colIndex] = userInput
isFound = True
break
print()
for x in self.myList:
print(x)
def remove(self):
print("Which box do you want to delete? Type in coordinates.")
x = int(input("Please enter a column: "))
x -= 1
y = int(input("Please enter a row: "))
y -= 1
self.myList[x][y] = 0
print()
for i in self.myList:
print(i)
menu()
def view(self):
for i in self.myList:
print(i)
menu()
array = Array()
def menu():
print()
print()
print()
print("****************")
print(" MENU")
print("****************")
print("Please choose:")
print("1. Add an item to the array")
print("2. Remove an item from the array")
print("3. View array")
print()
print("0. Quit")
print("****************")
option = int(input("Enter (1, 2 or 0): "))
print()
if option == 1:
array.input()
elif option == 2:
array.remove()
elif option == 3:
array.view()
elif option == 0:
quit()
else:
print("Error..")
menu()