[英]How to print a for loop in the function without using return in python?
I have a python program, which gets a value from an XML file and match it with the given code, but I don't know how to print the value with some conditions. 我有一个python程序,它从XML文件中获取一个值并将其与给定的代码匹配,但我不知道如何在某些条件下打印该值。
My Python program is: 我的Python程序是:
class setMap(getXml):
def __init__(self, event_log_row):
self.event_log_row = event_log_row
def code(self):
for each in self.event_log_row:
self.get_map(each)
# if I use return here, it basically returns only one value, which is understandable.
def get_map(self, event_code):
dict_class = getXml() # Getting XML from another class
dictionary = dict_class.getdescription()
for keys, values in dictionary.items():
if keys == event_code:
return values
# I'm not allowed to use for loop or any conditions after this
code = ['1011', '1015', '1013']
obj = setMap(code)
print(obj.code())
Is it possible to achieve what I am intend to achieve, can someone give me some suggestions, plz. 是否有可能实现我打算实现的目标,有人可以给我一些建议,PLZ。
Thanks 谢谢
You can use a list comprehension : 您可以使用列表理解 :
def code(self):
return [self.get_map(each) for each in self.event_log_row]
[print(x) for x in obj.code()]
If you get a result of 如果你得到了结果
result = [["One","Two"],["Three"], ["Four","Five","Six"]] # obj.code() result
from your setMap.code()
you can print this using 从你的
setMap.code()
你可以打印这个
result = [["One","Two"],["Three"], ["Four","Five","Six"]]
print(*result, sep ="\n") # unpack outer list for printing
print( *(b for a in result for b in a), sep ="\n") # flatten inner lists, unpack
resulting in 导致
['One', 'Two']
['Three']
['Four', 'Five', 'Six']
One
Two
Three
Four
Five
Six
You specify a print-seperator of newline to get them into different lines, no string-join neeeded. 你指定了换行符的print-seperator来将它们分成不同的行,不需要字符串连接。
Details on sep: What does print(... sep='', '\\t' ) mean? 有关sep的详细信息: print(... sep ='','\\ t')是什么意思? or Doku print()
或Doku打印()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.