【问题标题】:How to slice python dictionary, based on existence of specific element如何根据特定元素的存在对python字典进行切片
【发布时间】:2020-10-10 16:29:39
【问题描述】:

我有这样的字典:

mydictionary = {0: header,
1: thumbnail, 
2: paragraph, 
3: header, 
4: thumbnail,
5: thumbnail, 
6: paragraph, 
7: paragraph}

我正在遍历字典,如果我找到一个段落,我想找到所有以前的缩略图,但只能找到上一个段落。

for x in mydictionary:
   if paragraph in mydictionary:
      find all the previous thumbnails up to previous paragraph

换句话说,在第 2 段,它将返回第 1 项

在第 6 段中,它将返回项目 4 和 5

在第 7 段中,不会返回任何内容

【问题讨论】:

    标签: python dictionary extract slice


    【解决方案1】:

    你可以这样做:

    mydictionary = {0: "header",
                    1: "thumbnail", 
                    2: "paragraph", 
                    3: "header", 
                    4: "thumbnail",
                    5: "thumbnail", 
                    6: "paragraph", 
                    7: "paragraph"}
    
    prev_thumbnails = []
    for key, value in mydictionary.items():
        if value == "thumbnail":
            prev_thumbnails.append(key)
        elif value == "paragraph":
            print(prev_thumbnails)
            prev_thumbnails = []
    #returns
    #[1]
    #[4, 5]
    #[]
    

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 2018-08-14
      • 1970-01-01
      相关资源
      最近更新 更多