在python中重新排列列表

时间:2014-03-25 06:45:35

标签: python list

我需要定义一个名为" dutch_flag"的函数。它采用颜色列表(红色,绿色和蓝色)和:

返回color_list重新排列,以便' red'首先是字符串,绿色'第二个和蓝色'第三

>>> color_list = ['red', 'green', 'blue', 'red', 'red', 'blue', 'red', 'green']
>>> dutch_flag(['red', 'green', 'blue', 'red', 'red', 'blue', 'red', 'green'])
>>> color_list
['red', 'red', 'red', 'red', 'green', 'green', 'blue', 'blue']

到目前为止,我已经想出了这个:

color_list = ['red','red','red','red','green','green','red','blue','green','red','blue','red','blue','blue']

def dutch_flag (ls):

#create a list of colors according to their priority
colors = ['red', 'green', 'blue']

#create a list that keeps track of the number color counts while looping
colorCounts = []

#create a temporary list which will be used to re-create color_list
temp_ls = []

#loop over each color to process color_list
for color in colors:                    #for each colors
    colorCounts.append(ls.count(color))     #remember the color count

    #now add the color (color-count) times to the temp list

    #for each count, append color to the temp_list
    for count in range(ls.count(color)):
        temp_ls.append( color )

#re-define list
ls = temp_ls

#free memory
del temp_ls, colors, colorCounts

#return result
return ls

问题是它没有"重新排列"输入列表。我找不到以这种方式重新排列的方法。

请建议我使用简单解决方案(或算法),以便像我这样的绝对初学者能够理解。

3 个答案:

答案 0 :(得分:2)

只需使用sorted作为关键字list.index

>>> color_list = ['red','red','red','red','green','green','red','blue','green','red','blue','red','blue','blue']

>>> colors = ['red', 'green', 'blue']
>>> sorted(color_list, key= colors.index)
['red', 'red', 'red', 'red', 'red', 'red', 'red', 'green', 'green', 'green', 'blue', 'blue', 'blue', 'blue']

>>> colors = ['green', 'blue', 'red']
>>> sorted(color_list, key= colors.index)
['green', 'green', 'green', 'blue', 'blue', 'blue', 'blue', 'red', 'red', 'red', 'red', 'red', 'red', 'red']

使用功能:

def dutch_flag(seq, order=('red', 'green', 'blue')):
    return sorted(seq, key= order.index)

#Re-assign the returned value to a variable
new_list = dutch_flag(['red', 'green', 'blue', 'red', 'red', 'blue', 'red', 'green'])

答案 1 :(得分:1)

以下是简单解决方案:您可以使用sort()对其进行排序(就地排序,换句话说,它将重新列入列表)并将True传递给参数reverse。您将获得预期的结果,因为这将按相反的顺序按字母顺序对字符串进行排序:

def dutch_flag(L):
    L.sort(reverse = True)

<强>演示:

>>> color_list = ['red', 'green', 'blue', 'red', 'red', 'blue', 'red', 'green']
>>> dutch_flag(color_list)
>>> color_list
['red', 'red', 'red', 'red', 'green', 'green', 'blue', 'blue']

答案 2 :(得分:0)

一个简单的sort()函数应该可以工作。

color_list = ['red', 'green', 'blue', 'red', 'red', 'blue', 'red', 'green']
color_list.sort(reverse=True)
print(color_list)
['red', 'red', 'red', 'red', 'green', 'green', 'blue', 'blue']