对不起,如果已经在某处提到过(我找不到它)。
我基本上想要从列表中列出一个项目,但它包括引号和括号(我不想要)。 这是我的数据:
inputData = {'red':3, 'blue':1, 'green':2, 'organge':5}
这是我的课程,可以根据键或值来查找项目。
class Lookup(dict):
"""
a dictionary which can lookup value by key, or keys by value
"""
def __init__(self, items=[]):
"""items can be a list of pair_lists or a dictionary"""
dict.__init__(self, items)
def get_key(self, value):
"""find the key(s) as a list given a value"""
return [item[0] for item in self.items() if item[1] == value]
def get_value(self, key):
"""find the value given a key"""
return self[key]
除括号外,它的工作正常。
print Lookup().get_key(2) # ['blue'] but I want it to just output blue
我知道我可以通过替换括号/引号(LookupVariable.replace("'", "")
)来做到这一点,但我想知道是否有更多的pythonic方法。
感谢。
答案 0 :(得分:4)
更改
return [item[0] for item in self.items() if item[1] == value]
到
return next(item[0] for item in self.items() if item[1] == value)
现在你要返回列表理解的结果 - list
。相反,您希望返回等效生成器表达式返回的第一个项目 - 这就是next
所做的。
编辑:如果你真的想要多个项目,请使用Greg的答案 - 但听起来我只是想要获得一个密钥 - 这是一个很好的方法
如果您希望它在该值不存在时引发StopIteration
错误,请将其保留为上述内容。如果您希望它返回其他内容(例如None
),请执行:
return next((item[0] for item in self.items() if item[1] == value), None)
答案 1 :(得分:3)
您正在打印返回的列表值,Python使用括号和引号进行格式化。仅打印列表中的第一个元素:
print Lookup.get_key(2)[0]
打印以逗号分隔的列表元素:
print ", ".join(str(x) for x in Lookup.get_key(2))
或
print ", ".join(map(str, Lookup.get_key(2)))