繁体   English   中英

Python获取元素数组的最快方法

[英]Python fastest way to gets element's array

我正在寻找将元素放入数组的最快方法。 假设我们有一个这样的类:

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)

有一个更好的方法吗?

这是一种方法:

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')]

使用列表理解 我还修改了您的示例,但是由于另一项编辑正在等待中而无法更新问题。

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")]

暂无
暂无

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

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