简体   繁体   English

Python:如果value是元组/列表而不是字符串,我该如何迭代

[英]Python: how do I iterate only if value is a tuple/list and not a string

I am currently trying to write a python script/small app that is supposed to read events, and then translate them to a different format. 我目前正在尝试编写一个python脚本/小应用程序,它应该读取事件,然后将它们转换为不同的格式。 I am also making us of this to dabble a bit in object oriented programming but I am far from an an expert. 我也让我们这个涉及面向对象编程,但我远非专家。

I am trying to use a dictionary as map to define the mapping between the source fields and the translated fields. 我试图使用字典作为地图来定义源字段和翻译字段之间的映射。

One of the source fields though (priority in the example) is required twice in the output. 其中一个源字段(示例中的优先级)在输出中需要两次。

class event():
    def __init__(self, description, priority):
        self.description = description
        self.priority = priority

        pass

    _translateMap = {
       'description': 'message',
       'priority' : ('priority', 'severity')
    }

    def translate(self):
       result = {}
       for key, value in self._translateMap.items():
           for field in value:
               result[field] = getattr(self, key)

       return result

if __name__ == '__main__':
    event1 = event('blahblah','3')
    print event1.translate()

this will print: {'a': 'blahblah', 'e': 'blahblah', 'severity': '3', 'g': 'blahblah', 'm': 'blahblah', 'priority': '3', 's': 'blahblah'} 这将印刷: {'a': 'blahblah', 'e': 'blahblah', 'severity': '3', 'g': 'blahblah', 'm': 'blahblah', 'priority': '3', 's': 'blahblah'}

what I would like to have though is: {'message': 'blahblah', 'severity': '3', 'priority': '3'} 我想要的是: {'message': 'blahblah', 'severity': '3', 'priority': '3'}

I understand that the problem is iterating through every character of 'message', I am not really sure though what is the best way to avoid this while still being able to parse multiple input values? 我知道问题是遍历'消息'的每个字符,我不确定虽然仍然能够解析多个输入值的最佳方法是什么?

or is my expectation that they should work similarly is fundamentally wrong? 或者我期望他们应该同样工作从根本上是错误的? As mentioned I'm not very experienced yet so if you think the approach doesn't make sense let me know! 如上所述,我不是很有经验,所以如果你认为这种方法没有意义,请告诉我!

Thank you in advance, 先感谢您,

There are two ways you could fix this, you can make the 'message' string into a tuple, so your _translateMap would look like this: 有两种方法可以解决这个问题,你可以将'message'字符串变成一个元组,所以_translateMap看起来像这样:

_translateMap = {
    'description': ('message',),
    'priority' : ('priority', 'severity')
}

Otherwise, you could check the type with isinstance each time like this: 否则,你可以每次检查isinstance的类型,如下所示:

def translate(self):
    result = {}
    for key, value in self._translateMap.items():
        if isinstance(value,str):
            result[value] = getattr(self, key)
        else:
            for field in value:
                 result[field] = getattr(self, key)

    return result

I hope this helps. 我希望这有帮助。 :) :)

You can test whether the value is a string using isinstance: 您可以使用isinstance测试该值是否为字符串:

def translate(self):
    result = {}
    for key, value in self._translateMap.items():
        if isinstance(value,str):
            result[value] = getattr(self, key)
        else:
            for field in value:
                result[field] = getattr(self, key)

    return result

You don't need to have pass in the init dunder method. 您不需要pass init dunder方法。 - Also, indentation is the most important aspect when it comes to python since it interprets code based on the latter. - 另外,缩写是python最重要的方面,因为它根据后者解释代码。 - You can pass numbers to functions without using single quotes (string). - 您可以在不使用单引号(字符串)的情况下将数字传递给函数。

You can do something on the lines of: 你可以做以下几点:

def translate(self):
   return {field: getattr(self, value) for value, field in self._translateMap.items()}

Although I don't understand why you set the priority field as a tuple, you can do something like: 虽然我不明白为什么你将priority字段设置为元组,但你可以这样做:

class event():
    _translateMap = {
        'description': 'message',
        'priority': 'priority',
        'severity': 'severity'
    }


    def __init__(self, description, priority, severity):
        self.description = description
        self.priority = priority
        self.severity = severity

    def translate(self):
       return {field: getattr(self, value) for value, field in self._translateMap.items()}

if __name__ == '__main__':
    event1 = event('blahblah', 3, 5)
    print(event1.translate())

Give attention to how the numbers are not passed as strings and also if you'd like to add checks to the translate function you can. 注意如何将数字作为字符串传递,以及如果您想将检查添加到translate函数中。

I'm not sure about your use case but this will print the result as you want. 我不确定您的用例,但这会打印出您想要的结果。 You don't need to iterate through the variables. 您不需要遍历变量。 simply map everything you want in the first place. 只需首先映射您想要的所有内容。

class event():
    def __init__(self, description, priority):
        self.description = description
        self.priority = priority
        self.severity = priority

        pass

    _translateMap = {
       'description': 'message',
       'priority' : 'priority',
       'severity': 'severity'
    }

    def translate(self):
       result = {}
       for key, value in self._translateMap.items():
               result[key] = getattr(self, key)

       return result

if __name__ == '__main__':
    event1 = event('blahblah','3')
    print (event1.translate())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历元组<list<string> &gt; 在 Python </list<string> - How to iterate through Tuple<List<String>> in Python 如何在python中修改每个列表/元组中的第一个值? - How do I modify the first value in each list / tuple in python? 如何仅迭代元组列表中的第一个元组? - how to iterate ONLY the first tuple in a list of tuples? 如何根据元组中的值删除列表中的元组? - How do I delete a tuple in a list based on a value in the tuple? 我如何正则表达式搜索python值? “”“字符串”“”,“字符串”,“字符串”,(元组),[列表],{dict} - How do I regex search for python values? “”“string”“”, “string”, 'string', (tuple), [list], {dict} 如何将值列表迭代为字符串? - How do I iterate a list of values into a string? 如何在 Python 中以字符串形式编码的元组列表作为列表类型读取,元组作为元组类型读取? - How do I read list of tuples as list type and tuples as tuple type in Python that are encoded in the form of string? 如何在Python中迭代字符串? - How do I iterate through a string in Python? 如何迭代到列表中的元组 - How to iterate into a list into a tuple 迭代字符串元组和列表列表并将值导出到 Python 中的 csv - Iterate over a tuple of a string and list of lists and export values to a csv in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM