[英]How to slice python dictionary, based on existence of specific element
I have dictionary like this:我有这样的字典:
mydictionary = {0: header,
1: thumbnail,
2: paragraph,
3: header,
4: thumbnail,
5: thumbnail,
6: paragraph,
7: paragraph}
im looping through the dictionary and if I find a paragraph, I want to find all the previous thumbnails but only up to previous paragraph.我在字典中循环,如果我找到一个段落,我想找到所有以前的缩略图,但只能找到上一段。
for x in mydictionary:
if paragraph in mydictionary:
find all the previous thumbnails up to previous paragraph
in other words at paragraph 2, it would return item 1换句话说,在第 2 段,它将返回第 1 项
in paragraph 6, it would return item 4 and 5在第 6 段中,它将返回第 4 项和第 5 项
in paragraph 7, nothing will be returned在第 7 段中,不会返回任何内容
You can do something like this:你可以这样做:
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]
#[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.