我正在寻找将元素放入数组的最快方法。假设我们有这样一个类:
class test:
def __init__(self, a, b):
self.let = a
self.num = b
现在假设我们有一系列测试:
test1 = test("a", "1")
test2 = test("b", "2")
test3 = test("c", "3")
vec = [ test1, test2 , test3]
我希望结果是这样的:
newest = []
for t in vec:
if(t.let == "a" or t.num == "3")
newest.append(t)
有更好的方法吗?
答案 0 :(得分:0)
这是一种方式:
class test:
def __init__(self, let='', num=''):
self.let = let
self.num = num
test1 = test('a', '1')
test2 = test('b', '2')
test3 = test('c', '3')
vec = [test1, test2, test3]
newest = [i for i in vec if i.let == 'a' or i.num == '3']
newest_args = [(i.let, i.num) for i in newest]
# [('a', '1'), ('c', '3')]
答案 1 :(得分:0)
使用list comprehension。我还修改了您的示例,但由于另一个编辑处于待处理状态,因此无法更新问题。
class test:
def __init__(self, a, b):
self.let = a
self.num = b
test1= test("a","1")
test2= test("b","2")
test3= test("c","3")
vec = [ test1, test2 , test3]
newest = [t for t in vec if( t.let == "a" or t.num == "3")]