python动态变量名_Python列表变量名

1586010002-jmsa.png

I've been playing with Python and I have this list that I need worked out. Basically I type a list of games into the multidimensional array and then for each one, it will make 3 variables based on that first entry.

Array that is made:

Applist = [

['Apple', 'red', 'circle'],

['Banana', 'yellow', 'abnormal'],

['Pear', 'green', 'abnormal']

]

For loop to assign each fruit a name, colour and shape.

for i in Applist:

i[0] + "_n" = i[0]

i[0] + "_c" = i[1]

i[0] + "_s" = i[2]

When doing this though, I get a cannot assign to operator message. How do I combat this?

The expected result would be:

Apple_n == "Apple"

Apple_c == "red"

Apple_s == "circle"

Etc for each fruit.

解决方案

This is a bad idea. You should not dynamically create variable names, use a dictionary instead:

variables = {}

for name, colour, shape in Applist:

variables[name + "_n"] = name

variables[name + "_c"] = colour

variables[name + "_s"] = shape

Now access them as variables["Apple_n"], etc.

What you really want though, is perhaps a dict of dicts:

variables = {}

for name, colour, shape in Applist:

variables[name] = {"name": name, "colour": colour, "shape": shape}

print "Apple shape: " + variables["Apple"]["shape"]

Or, perhaps even better, a namedtuple:

from collections import namedtuple

variables = {}

Fruit = namedtuple("Fruit", ["name", "colour", "shape"])

for args in Applist:

fruit = Fruit(*args)

variables[fruit.name] = fruit

print "Apple shape: " + variables["Apple"].shape

You can't change the variables of each Fruit if you use a namedtuple though (i.e. no setting variables["Apple"].colour to "green"), so it is perhaps not a good solution, depending on the intended usage. If you like the namedtuple solution but want to change the variables, you can make it a full-blown Fruit class instead, which can be used as a drop-in replacement for the namedtuple Fruit in the above code.

class Fruit(object):

def __init__(self, name, colour, shape):

self.name = name

self.colour = colour

self.shape = shape

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值