【发布时间】:2021-07-12 03:07:07
【问题描述】:
我是一名学习 Python 的学生。我有一个处理数组的程序:
from array import *
adj_list = array('i', [])
def includeNode():
print('Enter the value')
k = int(input())
adj_list.append(k)
print('Your list:')
printList()
def includeNodeIndex():
print('Enter the value')
k = int(input())
print('Enter the index')
index = int(input())
adj_list.insert(index, k)
print('Your list:')
printList()
def deleteNode():
print('Enter the value')
k = int(input())
adj_list.remove(k)
print('Your list:')
printList()
def printList():
for i in adj_list:
print(i)
actions = {
'1': includeNode(),
'2': includeNodeIndex(),
'3': deleteNode()
}
print('Enter the number of elements')
num = int(input())
print('Enter ', num, ' elements')
for i in range(num):
k = int(input())
includeNode(k)
print('Your list:')
printList()
print('Enter 0 to exit. Enter 1 to delete an element. Enter 2 to add an element. Enter 3 to insert an element after index')
command = input()
while(command):
actions[command]
print('Enter 0 to exit. Enter 1 to delete an element. Enter 2 to add an element. Enter 3 to insert an element after index')
command = input()
我希望当我执行代码时,它会输出Enter the number of elements,然后我就可以使用我的数组了。但这不会发生。相反,程序输出Enter the value:这意味着它执行了我什至没有调用过的includeNode() 函数!
为什么会这样?这个函数不应该在它被调用的时候执行(而不是在它被声明的时候)?
【问题讨论】:
-
你在那里称呼它:
actions = { '1': includeNode(), '2': includeNodeIndex(), '3': deleteNode() } -
您也不需要使用
array模块。您可能来自其他语言,其中“数组”是您通常表示事物数组的方式。在 Python 中,we have/uselists.