[英]python if/else statement with exception that keep elements if exist in another sub-list
假设我在 list 中有以下标记:
['I', 'want', 'to', 'learn', 'coding', 'in', 'r', 'and', 'c++', 'today', ',', 'and', 'then', 'I', "'ll", 'be', 'learning', 'c#', 'and', 'c']
我想删除所有长度 < 2 的标记,但想保留此子列表的元素:
['r','c','js','c#']
如何在单个 python list-comprehension 中做到这一点?
您可以在两个条件下使用list comprehension
。
lst1 = ['I', 'want', 'to', 'learn', 'coding', 'in', 'r', 'and', 'c++', 'today', ',', 'and', 'then', 'I', "'ll", 'be', 'learning', 'c#', 'and', 'c']
lst2 = ['r','c','js','c#']
res = [l for l in lst1 if (len(l)>=2) or (l in lst2)]
print(res)
['want',
'to',
'learn',
'coding',
'in',
'r',
'and',
'c++',
'today',
'and',
'then',
"'ll",
'be',
'learning',
'c#',
'and',
'c']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.