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

Replace all elements of a two-item list with elements from another list

我正在学习 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():

时得到这个输出
Name: Veggie
Type: Vegetarian
Difficulty Level: Easy
Ingredients: Carrots, Lettuce, Tomato, Onions

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

name: Veggie
type: Vegetarian
difficulty_level: Easy
ingredients: lettuce, carrots, tomato, onions

提前致谢!

您的属性和值列表似乎是以下形式:

[['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]