python - 为什么我的 Python 列表中的某个元素被跳过?
问题描述
我正在创建一个程序来对我以列表形式给出的参数进行分类。现在,“选项”是紧跟在以 . 开头的参数之后的参数-
。“开关”是一个以 开头的参数--
。这是我的整个程序:
args = ['--encrypt', '-e', 'encryption', '-c', 'ceaser']
options = []
switches = []
def categoriseArgs():
global args, options, switches
for arg in args:
if arg.startswith('--'):
switches.append(arg)
del args[args.index(arg)]
elif arg.startswith('-'):
option = args[args.index(arg) + 1]
index = args.index(arg)
options.append(option)
del args[index]
del args[index]
categoriseArgs()
print(args)
print(options)
print(switches)
出于某种原因,我得到了这个输出:
['-e', 'encryption']
['ceaser']
['--encrypt']
'encryption'
也需要成为其中的一部分options
。而且不应该留下任何东西,args
因为我删除了元素。我试过调试这个,程序根本没有测试'-c'
,所以它和它后面的选项被忽略了。为什么会发生这种情况?
解决方案
您可以跟踪您已经看到的内容
args = ['--encrypt', '-e', 'encryption', '-c', 'ceaser']
options = []
switches = []
wasLastStartingWithSomething = False #Track what you have already seen
def categoriseArgs():
global args, options, switches, wasLastStartingWithSomething
for arg in args:
if arg.startswith('--'):
switches.append(arg)
wasLastStartingWithSomething = False
elif arg.startswith('-'):
wasLastStartingWithSomething=True
elif wasLastStartingWithSomething:
options.append(arg)
args = []
categoriseArgs()
print(args)
print(options)
print(switches)
[]
['encryption', 'ceaser']
['--encrypt']
推荐:这是根据OP在问题中给出的内容进行测试的!建议您对其进行测试以获取更多输入
此外,由于列表是可变的,您可以将它们作为参数传递给您的函数!def categoriseArgs(args, options, switches, wasLastStartingWithSomething):
args 也是一个特殊的名称,python 中函数定义中的 *args 用于将可变数量的参数传递给函数。
def myFun(*args):
for arg in args:
print (arg)
myFun('Hello', 'Welcome', 'to', 'StackOverFlow')
Hello
Welcome
to
StackOverFlow
推荐阅读
- javascript - R Shiny - 数据表中的子行(行数据未呈现)
- gdb - Debugging llvm with gdb but can't find source code
- svelte - How to pass parameters to on:click in Svelte?
- r - How to extract text between two words using str_extract?
- node.js - TypeError:无法在模型创建时读取未定义的属性“长度”
- java - Java stream iterating over a list most efficient way
- r - 在云端持续运行 R 脚本
- c++ - 如何解决我收到的错误:“意外的令牌 '=' 预期表达式”。使用模板和链表
- html - 使按钮成为蓝条的大小?
- c# - 添加登录视图