【问题标题】:Giving a string that changes a string variable给出一个改变字符串变量的字符串
【发布时间】:2022-01-04 08:59:48
【问题描述】:

我有一个我想传递给一些变量的名称列表,但是这些变量都有一个唯一的名称。我正在迭代,因为在这个例子中变量似乎很少,但在我的实际场景中,写出来并分配一个列表值会很多。

names = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]

n1=q1=t1=""
n2=q2=t2=""
n3=q3=t3=""

name = 0
quantity = 1
total = 2

value = len(names)
value = (value // 3) + 1

for i in range(1, value):
    tempN = "n" + str(i)
    tempQ = "q" + str(i)
    tempT = "t" + str(i)

    # using locals(), when i print the variables, n1, q1, t1...they all end up empty .
    # using exec() I get this error, all the examples to solve this error wasn't very helpful 
    # since most of them had to do with input from the user.
    #    File "<string>", line 1, in <module>
    #    NameError: name 'apple' is not defined

    locals()[tempN] = names[name]
    locals()[tempQ] = names[quantity]
    locals()[tempT] = names[total]
    exec("%s = %s" % (tempN, names[name]))
    exec("%s = %s" % (tempQ, names[quantity]))
    exec("%s = %s" % (tempT, names[total]))

    name += 3
    quantity += 3
    total += 3

这有点过于简单化了,但想法保持不变,我有许多变量需要从列表中获取值。一切都可以改变,除了列表格式,或者它是一个列表的事实。

有没有人知道更好的方法或解决我的问题?

【问题讨论】:

    标签: python variables exec


    【解决方案1】:

    您应该使用 Python 的数据结构,尤其是 dictionaries,这通常会导致编写的代码比使用 eval 函数的代码更少,并且使您的代码更具可读性。

    from collections import defaultdict
    
    result = defaultdict(dict)
    keys = ['name', 'quantity', 'total']
    names = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
    
    for i, values in enumerate(
        [names[x:x + len(keys)] for x in range(0, len(names), len(keys))]
    ):
        result[i] = dict(zip(keys, values))
    print(result)
    

    输出:

    defaultdict(<class 'dict'>,
                {0: {'name': 'apple', 'quantity': 1, 'total': 50},
                 1: {'name': 'boat', 'quantity': 5, 'total': 90},
                 2: {'name': 'tree', 'quantity': 4, 'total': 96}})
    

    【讨论】:

      【解决方案2】:

      我认为将列表拆分为子列表可以帮助您

      list = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
      sublists = [list[x:x+3] for x in range(0,len(list),3)]
      for element in sublists:
         print(element)
      

      输出

      ['apple', 1, 50]
      ['boat', 5, 90]
      ['tree', 4, 96]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-17
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-29
        相关资源
        最近更新 更多