Aligning two lists in python

好久不见. 提交于 2021-02-11 05:14:40

问题


I have a two Lists one with truth values and other containing experimental results and their associated scores.

truth = [6, 8, 7, 10]
experiment = [(6, 5), (4, 3), (2, 4), (11, 6), (7, 4)]

I want to align my experiment and truth values such that maximum truth value align

        [6, 8, 7, 10]
        [6, missing, 7, missing]

Now I'd like to assign value to missing from the from among subsequences which are not aligned.

Here we chose 11 from among (4, 3), (2, 4), (11, 6) since it has the highest score. The last missing value is assigned 0 because no element lies beyond (7, 4)

truth = [6, 8, 7, 10]
exp  =  [6, 11, 7, 0]   # Zero because 7 is the last element of experiment subsequence.

I was looking in difflib library but didn't understand much. How should I go about this?


回答1:


For the first part, you can do something like this:

truth = [6, 8, 7, 10]
experiment = [(6, 5), (4, 3), (2, 4), (11, 6), (7, 4)]

def prepare(exp):
    keys = [i for i, j in exp]
    def select(v):
        return v if v in keys else None
    return select

select = prepare(experiment)

exp = [select(i) for i in truth]

# exp will be [6, None, 7, None]



回答2:


Assuming that you'll never have two or more missing values next to each other, you can use:

truth = [6, 8, 7, 10]
experiment = [(6, 5), (4, 3), (2, 4), (11, 6), (7, 4)]

exp_list = [x[0] for x in experiment] #[6, 4, 2, 11, 7]

# Part one.
exp = [t if t in exp_list else None for t in truth] #[6, None, 7, None]

# Part two.
for i, t in enumerate(exp):
    if t == None:
        # Get index of previous and next truth values for missing values.
        i_prev = exp_list.index(exp[i-1]) if i else 0
        i_next = exp_list.index(exp[i+1]) if i < len(exp)-1 else len(exp_list)
        # Pick the largest value between them or 0 if no values are there.
        values_between = exp_list[slice(i_prev + 1, i_next)]
        exp[i] = max(values_between) if values_between else 0

print exp #[6, 11, 7, 0]



回答3:


The first part could be done with a simple list comprehension:

truth = [6, 8, 7, 10]
experiment = [(6, 5), (4, 3), (2, 4), (11, 6), (7, 4)]
res1 = [x if x in dict(experiment) else None for x in truth]

... or if you prefer lambda functions:

truth = [6, 8, 7, 10]
experiment = [(6, 5), (4, 3), (2, 4), (11, 6), (7, 4)]
res1 = map(lambda x: x if x in dict(experiment) else None, truth)


来源:https://stackoverflow.com/questions/24920350/aligning-two-lists-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!