[英]Filtering the list items python
i need to select the list contents with (gr,bl,wh) two lettres.我需要 select 列表内容与(gr,bl,wh)两个字母。 by excluding the words greater than two letters.i have a list that is in the given format..Any suggestion will help.通过排除大于两个字母的单词。我有一个给定格式的列表。任何建议都会有所帮助。
[red, gr, yellow]
[blue, wh, rose]
[orange, res, pink]
[red, bls, black]
[orange, re, pink]
[orange, re, pink]
the out put should look like输出应该看起来像
[red, gr, yellow]
[blue, wh, rose]
[orange, re, pink]
[orange, re, pink]
You can use a conditional list comprehension to filter the sublists where the length of second item is not equal to two.您可以使用条件列表推导来过滤第二项长度不等于 2 的子列表。
my_lists = [
['red', 'gr', 'yellow'],
['blue', 'wh', 'rose'],
['orange', 'res', 'pink'],
['red', 'bls', 'black'],
['orange', 're', 'pink'],
['orange', 're', 'pink'],
]
>>> [sublist for sublist in my_lists if len(sublist[1]) == 2]
[['red', 'gr', 'yellow'],
['blue', 'wh', 'rose'],
['orange', 're', 'pink'],
['orange', 're', 'pink']]
You can use a list comprehension to filter l
:您可以使用列表推导来过滤l
:
>>> l = [['red','blue','green'],['red', 're', 'blue']]
>>> [x for x in l if any(len(w) == 2 for w in x)]
[['red', 're', 'blue']]
Which filters sublists that have any()
word with a length of 2哪个过滤子列表包含any()
长度为 2 的单词
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.