【问题标题】:Idiomatic way to return the element before an element that matches a function in a list在与列表中的函数匹配的元素之前返回元素的惯用方式
【发布时间】:2012-02-15 08:49:03
【问题描述】:

假设我有这个输入:

d=['List', 'of', 'devices', 'attached', '33ddd323514d7', 
   'device', '8742323455', 'device']

并且我想返回在值等于'device'的列表元素出现之前直接出现的所有列表元素[在这种情况下,它将是与'33ddd323514d7'和'8742323455的值相对应的元素']。做这个的最好方式是什么?现在我这样做:

[i[0] for i in zip(d[:-1],d[1:]) if i[1]=="device"]

有没有更简单、更惯用的方法(或标准库函数)来完成这类事情?

【问题讨论】:

  • 您要返回的“数字”是什么?
  • 意思是“列表元素”,固定在上面

标签: python-3.x


【解决方案1】:

这个怎么样?

d[d.index("devices") - 1]

编辑:全部获取:

d[:d.index("devices")]

【讨论】:

  • “我想返回列表元素”。这只是一个:)
【解决方案2】:

您可以使用生成器。不是 oneliner,但速度快了大约 5 倍。

def getPrevGenerator(l, e):
    if l:
        prev = l[0]
        for cur in l[1:]:
            if cur == e:
                yield prev
            prev = cur

def getPrevWithZip(l, e):
    return [i[0] for i in zip(d[:-1],d[1:]) if i[1]==e]


e = 'device'
d=['List', 'of', 'devices', 'attached', '33ddd323514d7', 
   'device', '8742323455', 'device']

import timeit, functools
n = 10000
print('getPrevWithZip %f' % timeit.timeit(functools.partial(getPrevWithZip, d, e), number=n))
print('getPrevGenerator %f' % timeit.timeit(functools.partial(getPrevGenerator, d, e), number=n))

>>>> getPrevWithZip 0.060799
>>>> getPrevGenerator 0.011307

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-15
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多