如何在变量名中包含另一个变量名?

2024-10-04 03:20:17 发布

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

以下是我所拥有的:

names1 = ['bob', 'jack', 'adam', 'dom' ]


num = int(input('Please select a number? ')) # select number 1

for name in names + num: # This is where my problem is
    print (s)

我希望names+num部分引用names1列表。你会怎么做?你知道吗

任何帮助都将不胜感激!你知道吗


Tags: namenumberforinputnamesisselectnum
3条回答
names1 = ['bob', 'jack', 'adam', 'dom' ]

num = int(input('Please select a number? ')) # select number 1
name_array = "names" + str(num)
for name in name_array: # This is where my problem is
    print(name)

这里我们刚刚连接了name_array值。希望对你也有用。你知道吗

有两个选项,您可以使用nested list结构或dictionary。你知道吗

嵌套列表:

parent_list = [['bob', 'jack', 'adam', 'dom'], ["alpha", "beta", "gamma"], ["India", "USA"]]
num = int(input('Please select a number? '))
#Checking if the value entered can be accessed or not.
if num<3:
    for name in parent_list[num]:
        print name
else:
    print "Please enter a number between 0-2"

词典:

parent_dict = {0:['bob', 'jack', 'adam', 'dom'], 1:["alpha", "beta", "gamma"], 2:["India", "USA"]}
num = int(input('Please select a number? '))

if num<3:
    for name in parent_dict[num]:
        print name
else:
    print "Please enter a number between 0-2"

如果已经在脚本中创建了变量,则可以选择创建字典或变量嵌套列表:

names1 = ['bob', 'jack', 'adam', 'dom' ]
names2 = ["alpha", "beta", "gamma"]
names3 = ["India", "USA"]

#For nested list part
parent_list = [names1, names2, names3]

#For dictionary part
parent_dict = {0:names1, 1:names2, 2:nmaes3}

正确的方法是使用list或dict数据结构来存储一组选项,然后编写一个简单的函数来提示用户输入,并根据“有效选项”进行验证。你知道吗

示例:

from __future__ import print_function

try:
    input = raw_input
except NameError:
    input = raw_input  # Python 2/3 compatibility

names = ["bob", "jack", "adam", "dom"]

def prompt(prompt, *valid):
    try:
        s = input(prompt).strip()
        while s not in valid:
            s = input(prompt).strip()
        return s
    except (KeyboardInterrupt, EOFError):
        return ""

choices = list(enumerate(names))
print("Choices are: {0}".format(", ".join("{0}:{1}".format(i, name) for i, name in choices)))

try:
    s = prompt("Your selection? ", *(str(i) for i, _ in choices))
    i = int(s)
except ValueError:
    print("Invalid input: {0}".format(s))
else:
    print("Thanks! You selected {0}".format(choices[i][1]))

演示:

$ python foo.py
Choices are: 0:bob, 1:jack, 2:adam, 3:dom
Your selection? 0
Thanks! You selected bob

$ python foo.py
Choices are: 0:bob, 1:jack, 2:adam, 3:dom
Your selection? foo
Your selection? 1
Thanks! You selected jack

This also correctly handles the scenario of invalid inputs and int() throwing a ValueError as well as silencing ^D (EOFError) and ^C (KeyboardInterrupt) exceptions.

注意:你可以做for name in eval("names{0:d}".format(num)):但是不要这样做,因为使用eval()任意评估输入被认为是邪恶的,非常危险的。见:Is using eval() in Python bad pracice?

相关问题 更多 >