Python自定义getop

2024-04-16 16:38:11 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我是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"] 

但当我试图在多个选项之后立即传递它们时,就行不通了。上面的主代码是它不工作时的一个示例。你能解释一下为什么它只在某些时候起作用而在其他时候不起作用吗?任何帮助都将不胜感激。谢谢你


Tags: 函数getstring选项编程args字符remove
1条回答
网友
1楼 · 发布于 2024-04-16 16:38:11

问题

问题是在遍历列表时不能从列表中删除

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从字符串更改为列表。这样看来很有道理。你可以遍历它,计算成员数,等等。如果你想的话,你可以把它放回原来的方式(每个选项都连接一个字符串)

相关问题 更多 >