List 用另一个列表中的元素替换两项列表中的所有元素

List 用另一个列表中的元素替换两项列表中的所有元素,list,python-2.7,replace,key,List,Python 2.7,Replace,Key,我正在学习Python中的类,并决定创建一个类只是为了练习,但在以特定方式显示实例属性时遇到了问题: from abc import ABCMeta, abstractmethod class Salad(object): __metaclass__ = ABCMeta seasoning = ["salt", "vinegar", "olive oil"] # default seasoning def __init__(self, name, typ

我正在学习Python中的类,并决定创建一个类只是为了练习,但在以特定方式显示实例属性时遇到了问题:

from abc import ABCMeta, abstractmethod

class Salad(object):

    __metaclass__ = ABCMeta

    seasoning = ["salt", "vinegar", "olive oil"]      # default seasoning

    def __init__(self, name, type, difficulty_level, ingredients):
        self.name = name
        self.type = type
        self.difficulty_level = difficulty_level
        self.ingredients = ingredients

    def prepare(self, extra_actions=None):
        self.actions = ["Cut", "Wash"]
        for i in extra_actions.split():
            self.actions.append(i)
        for num, action in enumerate(self.actions, 1):
            print str(num) + ". " + action

    def serve(self):
        return "Serve with rice and meat or fish."


    # now begins the tricky part:

    def getSaladattrs(self):
        attrs = [[k, v] for k, v in self.__dict__.iteritems() if not k.startswith("actions")]     # I don't want self.actions

        sortedattrs = [attrs[2],attrs[1], attrs[3], attrs[0]]
        # sorted the list to get this order: Name, Type, Difficulty Level, Ingredients

        keys_prettify = ["Name", "Type", "Difficulty Level", "Ingredients"]
        for i in range(len(keys_prettify)):
            for key in sortedattrs:
                sortedattrs.replace(key[i], keys_prettify[i])
            # this didn't work


    @abstractmethod
    def absmethod(self):
        pass



class VeggieSalad(Salad):

    seasoning = ["Salt", "Black Pepper"]

    def serve(self):
        return "Serve with sweet potatoes."



vegsalad = VeggieSalad("Veggie", "Vegetarian","Easy", ["lettuce", "carrots", "tomato", "onions"])
基本上,我希望在调用vegsalad.getSaladattrs()时获得此输出:

而不是这样(如果我简单地告诉python使用for循环显示键和值,就会得到这个结果):


提前谢谢

您的属性和值列表的形式如下:

[['name', 'Veggie'], ['type', 'Vegetarian'], ['difficulty_level', 'Easy'], ['Ingredients', 'Carrots, Lettuce, Tomato, Onions' ]]
因此,以下内容应产生您想要的输出:

for e in attrs:
    if '_' in e[0]:
        print e[0][:e[0].find('_')].capitalize() + ' ' \
        + e[0][e[0].find('_') + 1:].capitalize() + ': ' + e[1]
    else:    
        print e[0].capitalize() + ': ' + e[1]

没问题,很高兴有帮助!
[['name', 'Veggie'], ['type', 'Vegetarian'], ['difficulty_level', 'Easy'], ['Ingredients', 'Carrots, Lettuce, Tomato, Onions' ]]
for e in attrs:
    if '_' in e[0]:
        print e[0][:e[0].find('_')].capitalize() + ' ' \
        + e[0][e[0].find('_') + 1:].capitalize() + ': ' + e[1]
    else:    
        print e[0].capitalize() + ': ' + e[1]