切片列表包括之前的两个项目和指定项目之后的两个项目包裹?

时间:2016-02-14 05:07:27

标签: python list

我有一个包含整数键和列表值的字典。我想能够遍历列表,如果我找到一个匹配我输入的条目,我想在指定的,指定的和之后的两个项目之前打印/存储两个项目,从而存储一个新的五个列表。我希望这可以环绕,以便如果匹配是列表中的最后一个,它将获得列表的最后三个和列表中的前两个。我无法弄清楚。

strings = {1:['e','f','fsharp','g','gsharp','a','asharp','b','c','csharp','d','dsharp'],
       2:['a','asharp','b','c','csharp','d','dsharp','e','f','fsharp','g','gsharp'],
       3:['d','dsharp','e','f','fsharp','g','gsharp','a','asharp','b','c','csharp'],
       4:['g','gsharp','a','asharp','b','c','csharp','d','dsharp','e','f','fsharp'],
       5:['b','c','csharp','d','dsharp','e','f','fsharp','g','gsharp','a','asharp'],
       6:['e','f','fsharp','g','gsharp','a','asharp','b','c','csharp','d','dsharp']}

usr_note = input("Enter note: ")

surrounding_notes = strings[1][strings[1].index(usr_note)-2:strings[1].index(usr_note)+2]

1 个答案:

答案 0 :(得分:0)

尝试:

def surroundings(st,i):
    if i<2:
        return st[i-2:] + st[:i+3]
    if i+2 >= len(st):
        return st[i-2:] + st[:i+3-len(st)]

    return st[i-2:i+3]

usr_note = 'f'
i = strings[1].index(usr_note)
surrounding_notes = surroundings(strings[1], i)
print surrounding_notes

usr_note = 'd'
i = strings[1].index(usr_note)
surrounding_notes = surroundings(strings[1], i)
print surrounding_notes

usr_note = 'c'
i = strings[1].index(usr_note)
surrounding_notes = surroundings(strings[1], i)
print surrounding_notes