关于代码结构的建议,以防止代码重复(Python,列表)

fdm*_*ion 1 python structure list

游戏中的场景是我有一个有序的项目列表.我想将该列表转换为单个字符串.

然而.

这不仅仅是将每个项目转换为字符串并连接的问题.作为转换的一部分,我需要在列表上进行一些处理.

这是一个粗略的例子:

列表:

[1, 
 2,
 3,
 0,
 1,
 9,
 -4,
 3,
 2]
Run Code Online (Sandbox Code Playgroud)

我想要的输出是这样的:

The total of a group is 6.
The total of a group is 10.
The total of a group is 5.
Run Code Online (Sandbox Code Playgroud)

这是我写的代码可以做到这一点:

total = 0
result = ""
for item in myList:
    if (item <= 0):
        result += "The total of a group is %d.\n" % total
        total = 0
        continue
    total += item

# NOTICE THE CODE DUPLICATION HERE...
result += "The total of a group is %d.\n" % total

print result
Run Code Online (Sandbox Code Playgroud)

问题是我result +=在代码中有两次.原因是我们无法保证列表中的最后一项是一个会导致实际附加字符串的代码执行的项目.(即我们无法保证数字为0或更低.)

对此的明显解决方案可能是"检查列表中的最后一项,如果它不是<= 0,则添加0作为最后一项." 这将适用于这样的基元列表.然而,它不适用于对象列表或复杂类型,或者比较简单而不是简单地<= 0.

所以问题是:有没有一种很好的方法来构造这样的代码,这样我就不会复制代码,这当然会带来很大的错误可能性?

谢谢!

F

Jon*_*nts 7

如果您被允许,您可以使用itertools.groupby分组正数,例如:

from itertools import groupby

data = [1, 2, 3, 0, 1, 9, -4, 3, 2]
group_totals = [sum(g) for k, g in groupby(data, lambda L: L > 0) if k]
for group_total in group_totals:
    print 'The sum of a group is', group_total
print 'Total of all groups is', sum(group_totals)
Run Code Online (Sandbox Code Playgroud)