繁体   English   中英

Python递归字符串连接

[英]Python recursive string concatenation

我正在使用python类生成用于日历每日视图的HTML表。 为了生成表,我递归地调用我的函数,直到达到期望的结束为止。 我看起来像这样:

# By default time=[0][0] and end_time=[0][24]
---------------------------------------------
def makeRows(self, time, end_time): # time/end_time = [min][hour] 
        row = ['<tr><td>']
        if time[1] == end_time[1]:  # Base case
            # String format
            if time[0] == 0:
                row.append('%s:00' % time[1])
            else:
                row.append('%s:%s' % (time[1], time[0]))

            row.append('</td></tr>')

            return format_html(''.join(row))
        else:   # Recursive case

            if time[0] == 0 and time[1] == 0: # First row
                row.append('0:00')
                row.append('</td><td rowspan="97"><div class="day_event_container"></div></td></tr>')
            else:
                # String format
                if time[0] == 0:
                    row.append('%s:00' % time[1])
                else:
                    row.append('%s:%s' % (time[1], time[0]))

                row.append('</td></tr>')

            return format_html(''.join(row)+self.makeRows(self.increaseTime(time), end_time))

def increaseTime(self, time):
        hour = time[1]
        minute = time[0]

        if minute == 0:
            minute+= 30
        else:
            hour += 1
            minute = 0

        return [minute, hour]

最近,我将所有字符串连接从+=更改为''.join()但唯一的“天真”连接在我的递归调用中。

该函数通常被调用48次以从0:00 -> 24:00 -> 24:00生成行

我的递归调用中的“天真”级联真的对48个函数调用来说真的很昂贵吗?

如果实际上我的“天真”连接非常昂贵,我该如何替换呢?

我试着做

return format_html(''.join(row).join(self.makeRows(self.increaseTime(time), end_time)))

但这会引发Exception Type: MemoryError并且我猜想它只会溢出堆或堆栈或其存储的任何地方。

最后,我对python还是很陌生,我99%的确定这与pythonic做事方式相去甚远。 那么,还有一种更Python化的方法来生成从0:0024:00的每日日历视图吗?

在我看来,您正在尝试取代-

format_html(''.join(row)+self.makeRows(self.increaseTime(time), end_time))

format_html(''.join(row).join(self.makeRows(self.increaseTime(time), end_time)))

但这是不正确的,两者都会返回不同的结果。 让我们举一个非常简单的例子来解释-

>>> ''.join('Bye').join('Hello')
'HByeeByelByelByeo'
>>> ''.join('Bye') + 'Hello'
'ByeHello'

我认为您应该保持+串联运算符的当前用法,而不是试图使其表现更好,除非您要处理的字符串列表非常大,但事实并非如此。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM