替换嵌套列表中包含相同答案的项目

时间:2017-06-07 21:02:06

标签: python list for-loop

我有一个嵌套列表,如下所示:

data = [
['student 1', '"answer 0"', '"answer 2"', '"answer 2"', '"answer 0"'],
['student 2', '"answer 4"', '"answer 2"', '"answer 4"', '"answer 0"']]

我希望结果显示为:

data = [
['student 1', 'Blue', 'Up', 'Left', 'Football'],
['student 2', 'Red', 'Up', 'Right', 'Football']]

根据列表中的索引,它可以有不同的结果,但在数据中它可以包含相同的字符串。什么是完成这项任务的有效方法?

1 个答案:

答案 0 :(得分:0)

您可以创建一个简单的[index, answer, replacement]替换地图,例如:

replacement_map = {
    1: {'"answer 0"': "Blue",  # replacements for index 1
        '"answer 1"': "Green",
        '"answer 2"': "Yellow",
        '"answer 3"': "Purple",
        '"answer 4"': "Red"},
    2: {'"answer 0"': "Right",  # replacements for index 2
        '"answer 1"': "Left",
        '"answer 2"': "Up",
        '"answer 4"': "Down"},
    3: {'"answer 0"': "Up",  # replacements for index 3
        '"answer 1"': "Down",
        '"answer 2"': "Left",
        '"answer 4"': "Right"},
    4: {'"answer 0"': "Football",  # replacements for index 4
        '"answer 1"': "Pocket billiard"}
}

data = [
    ['student 1', '"answer 0"', '"answer 2"', '"answer 2"', '"answer 0"'],
    ['student 2', '"answer 4"', '"answer 2"', '"answer 4"', '"answer 0"']
]

replaced_data = []  # we'll store our data here
for element in data:
    replaced_element = []
    for index, item in enumerate(element):
        if index in replacement_map:
            replaced_element.append(replacement_map[index].get(item, item))
        else:  # no replacement available for this index
            replaced_element.append(item)
    replaced_data.append(replaced_element)
# replaced_data contains:
# [['student 1', 'Blue', 'Up', 'Left', 'Football'],
#  ['student 2', 'Red', 'Up', 'Right', 'Football']]

如果你真的希望它尽可能高效,你可以通过列表理解来实现:

replaced_data = [[replacement_map.get(index, {}).get(item, item) for index, item in enumerate(element)] for element in data]

但是这不会给你带来很大的加速(事实上,根据替换地图,它可能会变慢)并且阅读起来很糟糕。