如何基于python中的优先级列表选择列中的元素?

时间:2019-06-18 20:24:06

标签: python list dataframe

我有一列,每行包含多个值。我正在尝试编写一个函数,根据优先级列表仅选择每一行的一个值,以便将其减少为一个值。我正在使用python。

我的专栏看起来像这样:

Green&Yellow
Yellow
Blue&Orange
Orange&Green
Purple&Green
Purple
Yellow&Purple
Green

我的优先级列表为:

Priority_list = [Green, Orange, Blue, Purple, Yellow ]

所需的输出将是:

Green
Yellow
Orange
Green
Green
Purple
Purple
Green

代码应如下所示:

def select_color(value):

    color = value.split('&')
    if len(color) > 1:
        my_color = first color found in list
    else:
        my_color = color

    return my_color

我找不到选择优先级列表中出现的第一个值的方法。

非常感谢

Rachael

3 个答案:

答案 0 :(得分:1)

您可以尝试更简单的方法:

import re
c = ["Green&Yellow","Yellow","Blue&Orange","Orange&Green","Purple&Green","Purple","Yellow&Purple","Green"]
p = ["Green", "Orange", "Blue", "Purple", "Yellow" ]
[[re.findall('(?i)(' + v + ').*?', x) for v in p if re.findall('(?i)(' + v + ').*?', x)][0][0] for x in c]

结果:

['Green', 'Yellow', 'Orange', 'Green', 'Green', 'Purple', 'Purple', 'Green']

答案 1 :(得分:0)

# list = Global list of colors that you want
# color = string col1&col2&col3...
def select_color(list, color):
    color_list = color.split('&')
    for col in color_list:
        if col in list:
            return col
    return

如果您将None作为返回值,则表示找不到颜色

答案 2 :(得分:0)

如果您在priority_list中使用所有颜色,则下面的代码将为您提供帮助

priority_list = [Green, Orange, Blue, Purple, Yellow ]

def select_color(value):

    color = value.split('&')
    if len(color) == 1:
        return color[0]
    else:
        for pcolor in priority_list:
            if pcolor in color :
                return pcolor;