简体   繁体   English

如果包含给定短语,则删除 python 中字符串列表的所有元素

[英]Remove all elements of a string list in python if they contain a given phrase

Have a list called summary containing a corresponding JSON object similar to:有一个名为summary的列表,其中包含类似于以下内容的相应 JSON 对象:

{
   # summary[0]
   "object1": {
      "json_data": "{json data information}",
      "tables_data": "TABLES_DATA"
   },

   # summary[1]
   "object2": {
      "json_data": "{json data information}",
      "tables_data": ""
   }
}

Essentially, if "tables_data": "" is found within the string of a list item, I want the entire list item to be removed.本质上,如果在列表项的字符串中找到"tables_data": "" ,我希望删除整个列表项。

How would I go about doing this?我该怎么做呢?

You can do a dictionary-comprehension selecting the dictionary item with 'tables_data' has a value not equals '' :您可以进行字典理解,选择带有'tables_data'的值不等于''的字典项:

summary = [{
   # summary[0]
   "object1": {
      "json_data": "{json data information}",
      "tables_data": "TABLES_DATA"
   },

   # summary[1]
   "object2": {
      "json_data": "{json data information}",
      "tables_data": ""
   }
}]
result = [{k: d for k, d in s.items() if d.get('tables_data') != ''} for s in summary]
# [{'object1': {'json_data': '{json data information}', 'tables_data': 'TABLES_DATA'}}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 python 删除字符串中包含任何给定子字符串的所有单词 - Remove all words in a string that contain any given substrings using python Python:如果列表包含字符串打印列表中包含它的所有索引/元素 - Python: if list contains string print all the indexes / elements in the list that contain it 快速删除给定python列表中所有元素的10%的快速方法 - fast way to uniformly remove 10% of all the elements in a given list of python 从字符串中删除短语列表 - Remove a list of phrase from string 使用Python从字符串列表中删除短语词典的更快方法 - Faster way to remove a dictionary of phrase from a list of string using Python 检查列表中的字符串是否包含另一个列表中的所有元素 - Check if string in list contain all the elements from another list 编写一个 Python 函数将给定列表的所有元素(最后一个元素除外)连接成一个字符串并返回该字符串 - Write a Python function to concatenate all elements (except the last element) of a given list into a string and return the string 如果元素包含特殊字符,则从 python 列表中删除元素 - Remove elements from python list if they contain special characters 删除列表中的元素,如果它们在 Python 中的其他列表中包含字符串模式 - Removing elements of list if they contain string pattern in other list in Python 从列表中删除除字符串之外的所有元素 - Remove all elements except string from list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM