下面的函数append将一个不可变元组对作为参数。在处理append时,有必要用起始和结束单引号将所有值括起来。因为元组值是不可变的,所以我不能简单地这样做:
if item[1][0] != "'" and item[1][-1] != "'":
item[1] = "'{0}'".format(item[1])
self.keyvalues[item[0]] = item[1]
因此,处理方法如下:
if item[1][0] != "'" and item[1][-1] != "'":
self.keyvalues[item[0]] = "'{0}'".format(item[1])
else:
self.keyvalues[item[0]] = item[1]
下面显示完整代码。你知道吗
有没有更优雅的方法来向字典添加键和值。你知道吗
class section(object):
"""class to hold a section. name is name of section. keyvalues is a key
value dictionary of keys and values"""
def __init__(self, name):
self.name = name
self.keyvalues = {}
print "Constructed section:", name
def append(self, item):
"""add a key value pair to section"""
if len(item) != 2:
return False
else:
print "adding:", item, "to", self.name, "object"
# cannot do this because tuple is immutable
#item[1] = "'{0}'".format(item[1])
# Would there be a more elegant way of doing this - given that
# parameter must be a immutable tuple?
if item[1][0] != "'" and item[1][-1] != "'":
self.keyvalues[item[0]] = "'{0}'".format(item[1])
else:
self.keyvalues[item[0]] = item[1]
return True
def __repr__(self):
s = "contains\n"
for k, v in self.keyvalues.iteritems():
s += "\t{0}={1}\n".format(k, v)
return s
__str__ = __repr__
mysection = section("section1")
dnpair = ("key1", "value1")
mysection.append(dnpair)
print mysection
优雅是主观的,但这是我能想到的最优雅的解决方案。它允许通过将值传递给函数来进行值操作。也是丑陋的
变成
下面是修改的
append
和新创建的quote_wrap
方法的完整代码。你知道吗由于元组不再使用,所以只需将其拆分为单独的变量。你知道吗
相关问题 更多 >
编程相关推荐