[英]Using startswith() function inside lists in python
I had the list with following strings below 我下面有以下字符串的列表
some_list = ['9196358485','9966325645','8846853128','8-4-236/2','9-6-32/45','Need to fetch some strings']
From the above strings i want only strings that does n't start with 91,9,8
but want strings starting with 8-, 9-
从上面的字符串中,我只希望不是以91,9,8
开头的字符串,而是想要以8-, 9-
开头的字符串
so below is my code 所以下面是我的代码
[i for i in some_list if all(not i.startswith(x) for x in ['91','8','9'])]
result : 结果 :
['Need to fetch some strings']
In the above by using ['91','8','9']
as the condition is deleting the strings starting with 9 and 8
which is correct, but i don't want 9-, 8-
also to be removed from the list, actually my intension is if the strings starting with 9 and 8
should be ignored as above and strings starting with 9- and 8-
should not be ignored , can we write two conditions in a single line with concept of taking strings starting with 8-,9-
and ignoring when strings starts with 9 or 8
in the above code i had written. 在上面通过使用['91','8','9']
作为条件是删除以9 and 8
开头的字符串,这是正确的,但是我不希望从中删除9-, 8-
列表中,实际上,我的意图是,是否应该像上面那样忽略以9 and 8
开头的字符串, 9 and 8
不应该忽略以9- and 8-
开头的字符串,我们是否可以在一行中编写两个条件,并采用以开头的字符串8-,9-
并忽略我在上面编写的代码中字符串何时以9 or 8
开头。
Can anyone please let me know hoe to do this............. 任何人都可以让我知道做这件事.............
Edited code: 编辑代码:
Thanks for all of ur support if u don't think this is another question i had some actual output on which the below code is not working 感谢您的所有支持,如果您不认为这是另一个问题,我有一些实际输出,以下代码不起作用
some_list = ['Mr K V Prasad Reddy(MD)',
'+(91)-9849633132, 9959455935',
'+(91)-9849633132',
'Near NRI College,Opp Vijaya Bank,Nizam Pet Road,Nizampet,Hyderabad - 502102',
'9196358485',
'9966325645',
'8846853128',
'8-4-236/2',
'9-6-32/45',
'Need to fetch some strings']
When i apply the bwlow code using regex i got following output result: 当我使用正则表达式应用bwlow代码时,得到以下输出结果:
['Mr K V Prasad Reddy(MD)',
'+(91)-9849633132, 9959455935',
'+(91)-9849633132',
'Near NRI College,Opp Vijaya Bank,Nizam Pet Road,Nizampet,Hyderabad - 502102',
'8-4-236/2',
'9-6-32/45',
'Need to fetch some strings']
Actually i don't want all phone numbers from the list, so they will be in the above format sometimes starting with 91
sometimes 8
sometimes 9
实际上,我不希望列表中包含所有电话号码,因此它们的格式有时是从91
开始,有时是8
有时是9
How can we remove all those phone numbers from the list? 我们如何从列表中删除所有这些电话号码?
Use a regular expression: 使用正则表达式:
>>> import re
>>> [i for i in some_list if not re.match(r"[98]\B|+\(91\)", i)]
['8-4-236/2', '9-6-32/45', 'Need to fetch some strings']
\\B
matches only within alphanumeric strings, so it matches between 9
and 1
but not between 9
and -
. \\B
仅在字母数字字符串内匹配,因此它在9
和1
之间匹配,但在9
和-
之间不匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.