gpt4 book ai didi

Python 自定义 getopt

转载 作者:行者123 更新时间:2023-12-01 04:10:46 26 4
gpt4 key购买 nike

你好,我是 python 编程新手,不知道如何使用 getopt。因此,由于我认为 python 是一种非常简单的语言,所以我决定编写自己的 getopt 函数。事情是这样的:

string = "a b -c -d"
list = string.split()

def get_short_opts(args):
opts = ""
for word in args:
print("Word = " + word)
if word[0] == '-' and word[1] != '-':
opts += word[1:] #to remove the '-'
args.remove(word)

print("Opts = " + opts)
print("Args = " + str(args))

return opts

print(get_short_opts(list))

基本上,该函数返回位于“-”字符之后的所有字符。当我一次使用多个选项且仅使用一个“-”并且如果我执行类似

的操作时,它会起作用
["-a", "arg", "-b"] 

但是当我尝试依次传递多个选项时,它不起作用。上面的主要代码是它不起作用的示例。你能解释一下为什么它只有时有效而有时无效吗?任何帮助,将不胜感激。谢谢!

最佳答案

问题

问题是您在迭代列表时无法从列表中删除。

参见this question ,特别是this answer引用the official Python tutorial :

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy.

(C++ 人们称之为“迭代器失效”,我不知道它的 Python 术语(如果有的话)。)

解决方案

迭代 args副本并从原始版本中删除:

string = "a b -c -d"
list = string.split()

def get_short_opts(args):
opts = []
for word in args[:]:
print("Word = " + word)
if word[0] == '-' and word[1] != '-':
opts.append(word[1:]) #to remove the '-'
args.remove(word)

print("Opts = " + str(opts))
print("Args = " + str(args))

return opts

print(get_short_opts(list))

args[:] 表示法是从 args 的开头到结尾的切片,换句话说,是整个内容。但切片是副本,而不是原始切片。然后,您可以像之前一样从原始 args 中删除,而不会影响迭代顺序。

另请注意,我已将您的 opts 从字符串更改为列表。这似乎是有道理的。您可以迭代它,计算成员数量等。如果您愿意,您可以将其放回原样(每个选项连接的字符串)。

关于Python 自定义 getopt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34982825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com