首页 > 解决方案 > 为什么我的 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',所以它和它后面的选项被忽略了。为什么会发生这种情况?

标签: python

解决方案


您可以跟踪您已经看到的内容

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

推荐阅读