用于过滤值中的文本的字典理解
Posted
技术标签:
【中文标题】用于过滤值中的文本的字典理解【英文标题】:Dictionary Comprehensions to filter text within the values 【发布时间】:2021-03-21 05:17:20 【问题描述】:我已经创建了字典列表 (all_quotes_i) ,并且想从“Scotty Pelley”中选择仅包含引号的元素
all_quote_i = []
#Each quote is given an index number
for idx, qte in enumerate(all_p):
qte = all_p[idx].getText()
all_quote_i.append('Index': idx, 'Quote': qte)
print(all_quote_i[5:8])
> ['Index': 5, 'Quote': 'Scott Pelley: (00:01)\nOn election night 2016,
> then President Barack Obama called Donald Trump at about three o’clock
> in the morning to congratulate him, even though Mr. Trump had lost the
> popular vote and took the electoral college by less than 1% in three
> states. Today, President Trump declines to accept the verdict of the
> voters despite losing by greater margins to President Elect Joe Biden.
> Mr. Obama hasn’t spoken of the election standoff until today. We spoke
> to the 44th president on the release of his new book, A Promised Land,
> a memoir of his early years and first term.', 'Index': 6, 'Quote':
> 'Speaker 2: (00:43)\nThe story will continue in a moment.', 'Index':
> 7, 'Quote': 'Scott Pelley: (00:48)\nWhat is your advice in this moment
> for President Trump?', 'Index': 8, 'Quote': 'Barack Obama:
> (00:54)\nWell, a president is a public servant. They are temporary
> occupants on the office by design. When your time is up, then it is
> your job to put the country first and think beyond your own ego and
> your own interests and your own disappointments. My advice to
> President Trump is if you want, at this late stage in the game to be
> remembered as somebody who put country first, it’s time for you to do
> the same thing.']
我想使用列表推导来仅选择 Scott Pelly 的“报价”: pelley_only = [v for k,v in all_quote_i if v.startswith('Scott Pelley')]
【问题讨论】:
您发布了大量代码,其中大部分似乎与您的要求无关。请read this 并创建一个您尝试解决的问题的最小示例,以便其他人可以帮助您。 那么问题到底是什么? 我想使用列表推导仅选择 Scott Pelly 的“报价”: pelley_only = [v for k,v in all_quote_i if v.startswith('Scott Pelley')] 【参考方案1】:这应该可行。
pelley_quotes = [quote["Quote"] for quote in quotes
if quote["Quote"].startswith("Scott Pelley")]
如果您想要包含引用的完整字典,您可以将 quote["Quote"]
更改为 quote
【讨论】:
@nhandy 没问题!非常感谢标记为解决方案和支持:) 我能够“投票”,但我不知道如何将您的答案标记为解决方案 @nhandy 您可以通过单击我的答案左侧的灰色复选标记(在赞成和反对按钮下方)将其标记为解决方案。该标记应变为绿色。 我的声望分数不够高,无法移动投票计数,但“已被记录”。以上是关于用于过滤值中的文本的字典理解的主要内容,如果未能解决你的问题,请参考以下文章