Python 从索引之间的旧词典创建新词典

Python creating new Dictionary from older one between indexes

我是 python 的新手,但我想知道如何解决这个问题。我想复制索引 4 和 20、20 和 25 之间的所有行,并将其作为值放入新字典中。

def cutting(my_sequence):    
    code={}
    text=dict(my_sequence) #converts my sequence which has line numbers as key and line as value
    list=[4,20,25] #holds line numbers I want to cut between
    #now what?Here is where I have to find out how to make a new dict with all the lines in between as value
    return code 

例如,

如果文本采用类似

的形式
{0:'hello guys this is the start\n',
 1:'this is the first line\n',
 2:'this is the second line\n'}

我想要这样的输出字典代码:

{0:'hello guys this is the start\n this is the first line\n',
 1:'this is the second line\n'}

看来词典在这里是错误的选择。让我们改用列表。由于我们忽略了原始行号,因此我们可以从它们在列表中的位置推断出它们。

def cutting(my_sequence: "list of tuples of form: (int, str)"): -> list
    flat_lst = [v for _, v in my_sequence]

这将构建一个仅包含文本的列表。现在让我们构建一个范围列表以使用

    lines_to_join = [5, 20, 25]
    ranges = [range(lines_to_join[i],
                    lines_to_join[i+1]) for i in range(len(lines_to_join)-1)]
    # ranges is now [range(5, 20), range(20, 25)]

有更漂亮的方法可以做到这一点(请参阅 itertools recipes 中的 pairwise 函数),但这适用于这个小应用程序

接下来,让我们用"\n".join把你想要的线条粘在一起。

    result = ["\n".join([flat_lst[idx] for idx in r]) for r in ranges]
    # you might want to strip the natural newlines out of the values, so
    # # result = ["\n".join([flat_lst[idx].strip() for idx in r]) ...]
    # I'll leave that for you
    return result

请注意,如果 ranges 中的任何索引落在 flat_lst 之外,这将抛出 IndexError

一起我们应该有这样的东西:

def cutting(my_sequence: "list of tuples of form: (int, str)"): -> list
    flat_lst = [v for _, v in my_sequence]lines_to_join = [5, 20, 25]
    ranges = [range(lines_to_join[i],
                    lines_to_join[i+1]) for i in range(len(lines_to_join)-1)]
    # ranges is now [range(5, 20), range(20, 25)]

    result = ["\n".join([flat_lst[idx] for idx in r]) for r in ranges]
    return result