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

时间:2015-11-08 18:20:33

标签: 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, 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

提前致谢!

1 个答案:

答案 0 :(得分:0)

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

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