是否有方法返回/打印不带引号或括号的列表项?

2024-05-18 22:13:58 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,如果这已经提到某处(我找不到)。

我基本上想从列表中列出一个项目,但它包括引号和括号(我不想)。 这是我的数据:

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("'", ""))来实现这一点,但我想知道是否有一种更像Python的方法来实现这一点。

谢谢。


Tags: keyselfgetbydictionaryvaluedefitems
2条回答

您正在打印返回的列表值,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)))

改变

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)

现在您返回的是列表理解的结果——alist。相反,您希望返回等价的生成器表达式返回的第一个项——这就是next所做的。

编辑:如果您确实需要多个项目,请使用Greg的答案——但在我看来,您似乎只想得到一个键——这是一个很好的方法。

如果您希望它在值不存在的情况下引发一个StopIteration错误,请将其保留为上述值。如果您希望它返回其他内容(例如None),请执行以下操作:

return next((item[0] for item in self.items() if item[1] == value), None)

相关问题 更多 >

    热门问题