如何在函数中打印for循环而不使用python中的return?

2024-09-27 22:31:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序,它从XML文件中获取一个值,并将其与给定的代码匹配,但我不知道如何在某些条件下打印该值。你知道吗

我的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())

有没有可能达到我想要达到的目标,有没有人能给我一些建议,请允许。你知道吗

谢谢


Tags: inself程序eventlogforgetdef
2条回答

如果你得到

result  = [["One","Two"],["Three"], ["Four","Five","Six"]]        # obj.code() result

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

导致

['One', 'Two']
['Three']
['Four', 'Five', 'Six']

One
Two
Three
Four
Five
Six

您可以指定换行符的打印分隔符以将它们放入不同的行中,不需要字符串联接。你知道吗

九月详情:What does print(... sep='', '\t' ) mean?Doku print()

您可以使用list comprehension

    def code(self):
        return [self.get_map(each) for each in self.event_log_row]

[print(x) for x in obj.code()]

相关问题 更多 >

    热门问题