簡體   English   中英

如何在不使用python返回的情況下在函數中打印for循環?

[英]How to print a for loop in the function without using return in 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())

是否有可能實現我打算實現的目標,有人可以給我一些建議,PLZ。

謝謝

您可以使用列表理解

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

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

如果你得到了結果

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

你指定了換行符的print-seperator來將它們分成不同的行,不需要字符串連接。

有關sep的詳細信息: print(... sep ='','\\ t')是什么意思? Doku打印()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM