繁体   English   中英

Python 2.7-从列表列表返回列表,其中子列表项包含某些字符

[英]Python 2.7 - return list from list of lists where sub-list item contains certain character

我有一长串名单,像这样的“人”:

persons = [['Boris', 'Jones', '988991'], ['Charlie', 'Smith', '999'], ['Sue', 'White', '9']]

我想从“人员”中提取仅包含允许字符的人员:

permitted = ['9']

结果应该是这样的:

result = [['Charlie', 'Smith', '999'], ['Sue', 'White', '9']]

这是我尝试过的。 显然它不起作用:(

permitted = ['9']

persons = [['Boris', 'Jones', '98991'], ['Charlie', 'Smith', '999'], ['Sue', 'White', '9']]

persons = [x for x in persons if x[field][-1] in permitted]
persons = [x for x in persons if x[field][-2] in permitted]
persons = [x for x in persons if x[field][-3] in permitted]
persons = [x for x in persons if x[field][-4] in permitted]
persons = [x for x in persons if x[field][-5] in permitted]
persons = [x for x in persons if x[field][-6] in permitted]

数字字段可以包含1到6个字符。

您可以这样做:

result = [i for i in persons if all(j in permitted for j in i[-1])]

persons = [['Boris', 'Jones', '988991'], ['Charlie', 'Smith', '999'], ['Sue', 'White', '9']]
permitted = ['9']

result = [i for i in persons if all(j in permitted for j in i[-1])]

>>> print result
[['Charlie', 'Smith', '999'], ['Sue', 'White', '9']]

希望能有所帮助。

在此,如果字符串中的所有字符都在permitted ,则all(...)仅求值为True否则为False

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM