【问题标题】:How to include a variable name inside a variable name? [duplicate]如何在变量名中包含变量名? [复制]
【发布时间】:2015-08-17 19:06:33
【问题描述】:

这是我所拥有的:

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 列表。你会怎么做?

任何帮助将不胜感激!

【问题讨论】:

  • “你会怎么做?”答:我们不会那样做。现在AFK,但我相信很快就会有人解释它。
  • XY 问题有更好的方法来做到这一点!
  • 这个问题没有第二个清单是无稽之谈。评论#select number 1 是... ...您希望什么?
  • 这被标记为与现有问题的重复。但是,应该注意的是,您所询问的方法并不是解决问题的好方法,并且已经给出的一些答案提出了一些更好的方法来使用正确的 数据结构我>。快乐的黑客攻击!

标签: python variables


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    正确的方法是使用列表或字典数据结构来存储一组选择,然后编写一个简单的函数来提示用户输入并根据“有效选择”。

    示例:

    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) 例外。

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

    【讨论】:

      【解决方案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 值。希望它也对你有用。

      【讨论】:

        【解决方案4】:

        使用此来源

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

        【讨论】:

        • 这不能回答所提出的问题。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 2013-11-26
        • 1970-01-01
        • 2014-10-08
        相关资源
        最近更新 更多