[英]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.