Python 颜色列表分区程序
假设我们有一个颜色字符串列表,这些字符串可能包含“红色”、“绿色”和“蓝色”,我们需要对列表进行分区,以便红色在绿色之前,绿色在蓝色之前。
因此,如果输入类似于 colors = ["blue","green", "blue", "red", "red"],则输出将为 ['red', 'red', 'green', 'blue', 'blue']
为了解决这个问题,我们将遵循以下步骤:
green := 0, blue := 0, red := 0
对于strs中的每个字符串,执行:
如果字符串与“red”相同,则:
strs[blue] := "blue"
blue := blue + 1
strs[green] := "green"
green := green + 1
strs[red] := "red"
red := red + 1
否则,如果字符串与“green”相同,则:
strs[blue] := "blue"
blue := blue + 1
strs[green] := "green"
green := green + 1
否则,如果字符串与“blue”相同,则:
strs[blue] := "blue"
blue := blue + 1
返回 strs
让我们看看下面的实现,以便更好地理解:
示例
class Solution: def solve(self, strs): green = 0 blue = 0 red = 0 for string in strs: if string == "red": strs[blue] = "blue" blue += 1 strs[green] = "green" green += 1 strs[red] = "red" red += 1 elif string == "green": strs[blue] = "blue" blue += 1 strs[green] = "green" green += 1 elif string == "blue": strs[blue] = "blue" blue += 1 return strs ob = Solution() colors = ["blue","green", "blue", "red", "red"] print(ob.solve(colors))
输入
["blue","green", "blue", "red", "red"]
输出
['red', 'red', 'green', 'blue', 'blue']
广告