如何在变量名中包含变量名?

时间:2015-06-03 14:00:29

标签: python variables

这就是我所拥有的:

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)

我希望名称+ num部分引用names1列表。你会怎么做?

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:3)

有两个选项,您可以使用,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}

答案 1 :(得分:1)

正确的方法是使用list或dict数据结构来存储一组选项,然后编写一个简单的函数,提示用户输入并根据&#验证它34;有效的选择&#34;。

示例:

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
  

这也正确处理无效输入的情况,int()抛出ValueError以及沉默^D EOFError )和^C KeyboardInterrupt )例外。

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

答案 2 :(得分:0)

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 值。希望它也适合你。

答案 3 :(得分:-2)

使用此来源

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


num = int(input('Please select a number? ')) # select number 1
for counter in range (num,4):
   print(names1[counter]);