Skip to main content
 首页 » 编程设计

python之打印 Python3 列表元素的内容而不是值

2025年01月19日9sharpest

我在 Python3 中有一个列表,其中包含两个变量,这些变量包含通过 argparse 设置的值:

start = set by user cli argument  
end = set by user cli argument 
 
arguments=[start,end] 
 
print (arguments[0]) 
print (arguments[1]) 

这目前只给出了用户通过命令行设置的开始和结束的整数值,但我还想打印变量名。我怎样才能做到这一点?最后,我试图检查用户是否通过 cli 设置了变量。我有一个 for 循环来遍历用户可能设置的所有可用参数。

arguments=[start,end] 
print (arguments[0]) //This (test) returns the integer the user set 
print (arguments[1]) //This (test) returns the integer the user set 
 
for x in arguments: 
    if results.arguments[x] is not None: //results.start and results.end are the variables coming from argparse 
        print ('User has set argument values via the CLI... Do something here.') //This is where I would actually use the integer value of arguments[x], but above in the if statement, I need the variable string from the array element. 
    else: 
        print ('User did not specify any arguments via the CLI. Pull the values from the config file.') 

** 示例 **

user@taco# python3 program.py -s 100 -e 1000 

用户运行程序并指定起始值为100,结束值为1000

parser = argparse.ArgumentParser(description='Taco help menu', add_help=True) 
parser.add_argument('-s', '--start', dest='start', action='store', help='enter the starting <value>', metavar='<value>') 
parser.add_argument('-e', '--end', dest='end', action='store', help='enter the ending <value>', metavar='<value>') 
results = parser.parse_args() 
 
arguments=[start,end] 

让我们用一些打印命令来检查我们所处的位置

print (arguments[0]) // Should output 100 
print (arguments[1]) // Should output 1000 
print (results.start) // Should also output 100 
print (results.end) // Should also output 1000 

现在我们需要检查用户是否设置了参数。为此,让我们检查 results.start 和 results.end 是否设置为 None。我们需要一个 for 循环来遍历所有可能的参数。目前只有两个(开始和结束),但谁知道呢,以后可能会有更多。

for x in arguments: 
    if results.arguments[x] is not None: 
        print ('User has set argument values via the CLI... Do something here.') //This is where I would actually use the integer value of arguments[x], but above in the if statement, I need the variable string from the array element. 
    else: 
        print ('User did not specify any arguments via the CLI. Pull the values from the config file.') 

* 更新 *

好吧,我取得了更多进展,但混淆了一些事情。我想我已经把它缩小到一个单一的、现在不同的问题了。使用 for 循环迭代变量获取数组元素。请参阅下面的完整代码和当前错误消息。笔记!!!如果我删除 for 循环并仅手动指定元素编号,一切正常。

parser = argparse.ArgumentParser(description='Taco help menu', add_help=True) 
parser.add_argument('-s', '--start', dest='start', action='store', help='enter the starting <value>', metavar='<value>') 
parser.add_argument('-e', '--end', dest='end', action='store', help='enter the ending <value>', metavar='<value>') 
results = parser.parse_args() 
 
arguments=[results.start,results.end] 
 
print (arguments[0]) 
print (arguments[1]) 
print (results.start) 
print (results.end) 
 
for x in arguments: 
    if arguments[x] is not None: // <-- This line seems to be the issue now. arguments[x] not working. 
        print ('CLI set') 
    else: 
        print ('Default config') 

这是我收到的当前错误消息:

user@taco# python3 program.py -s 100 -e 1000 
100 
1000 
100 
1000 
Traceback (most recent call last): 
  File "program.py", line 38, in <module> 
    if arguments[x] is not None: 
TypeError: list indices must be integers or slices, not str 

* 更新 *

顺便说一句...这(下面)在技术上通过首先避免它来解决问题哈哈。当然,现在每次向程序添加新参数时,也必须手动添加此列表。不理想。仍然想弄清楚这个 for 循环问题。

if results.start: 
    start = results.start 
if results.end: 
    end = results.end 

现在,当您通过 CLI 设置参数时,它会优先于配置文件中的值。

请您参考如下方法:

您正在尝试使用值而不是键访问列表,这在极少数情况下可能会起作用。由于 for 是一个 for each 循环,您已经在迭代列表中的项目。

这是错误的,x 并不表示键而是项目本身,如果您尝试编写“常规”for 循环,则需要遍历列表的长度而不是项目来获取每个键,就像使用任何其他语言一样:

Wrong: 
for x in arguments: 
    if arguments[x] is not None: 
 
foreach 
for x in arguments: 
    if x: 
        # Do stuff 
    else: 
        # Do other stuff 

像这样的方法可能更容易。

import argparse 
 
 
def import_config(): 
    return { 
        "start": 10, 
        "end": 100 
    } 
 
 
def do_stuff(start, end): 
    print(start, end) 
 
 
if __name__=="__main__": 
    config = import_config() 
    parser = argparse.ArgumentParser() 
    parser.add_argument("-s", type=int, dest="start", default=config["start"]) 
    parser.add_argument("-e", type=int, dest="end", default=config["end"]) 
    args = parser.parse_args() 
 
    do_stuff(args.start, args.end)