[英]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.