python - 打印Python列表

标签 python list

我必须初始化列表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/

相关文章:

Python:寻求文件中的 EOL 不起作用

javascript - 单击任何 <li> 元素时显示

swift 3 : Change item in dictionary

javascript - 获取上一个/下一个 |使用 list.js 的第一个/最后一个按钮

python - 我可以在分区的配置单元表上使用 mrjob python 库吗?

python - 尝试为 Python 3 安装 scikit-learn 时出现 "Cannot fetch index base URL"错误消息

python - 为什么新行 "\n"不适用于 Jython for WAS wasadmin

python - 如何在 Flask 中按下按钮时获取 HTML <tr> 标签?

C - 从数组中的文件加载数据

python - 如何将列表中的所有元素相互相乘?