Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中的列表中使用startswith()函数_Python_List - Fatal编程技术网

在python中的列表中使用startswith()函数

在python中的列表中使用startswith()函数,python,list,Python,List,我有下面带有字符串的列表 some_list = ['9196358485','9966325645','8846853128','8-4-236/2','9-6-32/45','Need to fetch some strings'] 从上面的字符串中,我只想要不以91,9,8开头的字符串,而想要以8-,9-开头的字符串 下面是我的代码 [i for i in some_list if all(not i.startswith(x) for x in ['91','8','9'])] 结果

我有下面带有字符串的列表

some_list = ['9196358485','9966325645','8846853128','8-4-236/2','9-6-32/45','Need to fetch some strings']
从上面的字符串中,我只想要不以
91,9,8
开头的字符串,而想要以
8-,9-
开头的字符串

下面是我的代码

[i for i in some_list if all(not i.startswith(x) for x in ['91','8','9'])]
结果

['Need to fetch some strings']
在上面使用
['91','8','9']
作为条件,删除以
9和8开头的字符串,这是正确的,但我不希望
9-,8-
也从列表中删除,实际上,我的意图是,如果以
9和8开头的字符串如上所述应该被忽略,并且以
9-和8-
开头的字符串不应该被忽略,那么我们可以在一行中写两个条件,以
8-开头的字符串为概念,9-
并在我编写的上述代码中忽略以
9或8开头的字符串

谁能告诉我怎么做

编辑的代码:

['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']
如果你不认为这是另一个问题,谢谢你的支持,我有一些实际的输出,下面的代码不起作用

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']
当我使用正则表达式应用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']
事实上,我并不想要列表中的所有电话号码,因此它们将采用上述格式,有时以
91
开头,有时以
8
开头,有时以
9


如何从列表中删除所有这些电话号码?

使用正则表达式:

>>> 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
仅在字母数字字符串中匹配,因此它在
9
1
之间匹配,但在
9
-

之间不匹配。如果您明确希望在9或8之后检查破折号,也可以使用正则表达式
[98](?!-)
。实际上,这很有效,但我在上面粘贴了一个真实的示例。您是否可以看到,通过使用上述代码,仅忽略以8和9开头的字符串,但如果我也忽略以+(91)开头的字符串,则该怎么办?在下面给出的正则表达式中,如何避免以+(91)开头的字符串我的意思是如何忽略以+(91)、9和8开头的字符串