我必须初始化列表L并遵循N行中给出的N条命令。
命令将是以下8条命令中的1条:
append
extend
insert
remove
pop
index
count
sort
reverse
请在下面找到我的代码。我只是一个初学者。请原谅我的错误。
样本输入为:
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
输出应为:
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
我的代码是:
L = []
L.insert(0,5)
L.insert(1,10)
L.insert(0,6)
print L
L.remove(6)
L.append(9)
L.append(1)
L.sort()
print L
L.pop()
L.reverse()
print L
即使它以某种方式完成了工作,也并不准确。如何简化呢?
最佳答案
显然问题是关于为这样的迷你语言编写解释器……
L = []
# read the number of commands
N = int(raw_input())
# execute N commands
for x in xrange(N):
# read a line and split on spaces
cmd = raw_input().split()
# process the command
if cmd[0] == "insert":
L.insert(int(cmd[1]), int(cmd[2]))
elif cmd[0] == "pop":
L.pop()
... implement all the commands ...
else:
raise RuntimeError("Unknown command " + repr(cmd))
关于python - 打印Python列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31355333/