删除列表中所有在python中不以数字结尾的元素
我试图通过删除1、2或3中没有结束的行来对数组进行排序。 到目前为止,我还不是很成功,我提出的代码如下所示: 这些行设置要在函数中使用的变量删除列表中所有在python中不以数字结尾的元素,python,list,Python,List,我试图通过删除1、2或3中没有结束的行来对数组进行排序。 到目前为止,我还不是很成功,我提出的代码如下所示: 这些行设置要在函数中使用的变量 import numpy as np A=[] B=[] C=[] file = open('glycine_30c.data', 'r') bondsfile = open('glycine_30c.bonds', 'r') 这些行将.data和.bonds文件读入数组 for lines in file: eq = lines.split(
import numpy as np
A=[]
B=[]
C=[]
file = open('glycine_30c.data', 'r')
bondsfile = open('glycine_30c.bonds', 'r')
这些行将.data和.bonds文件读入数组
for lines in file:
eq = lines.split()
A.append(str(eq))
for x in bondsfile:
bon = x.split()
B.append(str(bon))
这里的这些行(希望)删除列表“B”中所有不以1、2或3结尾的元素,然后将它们附加到新的列表“C”中,尽管这不是真的需要
for n in range(len(B)):
if B[n].endswith(1,2,3) == True:
C.append (B[n])
print C
非常感谢您的帮助。有关
endswith()的文档说明:
endswith(...)
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
即打电话
B[n].endswith(1,2,3)
不会实际检查B[n]
是否以1、2、3中的任何一个结尾。你可能想要的是类似于
B[n].endswith(("1", "2", "3"))
例如,传递一个元组参数。那么你得到的有什么问题吗?为什么要传递整数到str.endswith
?B[n]。endswith(1,2,3)
-你想在这里做什么?看看:str(B[n])。endswith(('1','2','3')以接受一个元组结尾。@ilent2:D'oh现在这样做了;我忘了将我的第一个(任何基于
的版本)替换为我从使用
文档实际查找结尾所学到的内容