【问题标题】:Looking for function to shorten the list寻找缩短列表的功能
【发布时间】:2018-05-31 09:51:16
【问题描述】:

wxPython 中的一些小部件有一个类似“GetSelections()”的方法,它返回所选项目的索引列表。 有了这个索引列表,我可以得到一个项目列表。这样,例如:

>>> list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five']
>>> list_of_indexes = [1,3,5]
>>> [list_of_items[e] for e in list_of_indexes]
['one', 'three', 'five']

所以问题是:最后一个字符串有快捷方式吗?比如:

list_of_items.getitems(list_of_indexes)

谢谢!

【问题讨论】:

    标签: python python-3.x list indexing wxpython


    【解决方案1】:

    您可以使用的方法很少。

    列表切片

    [1, 3, 5] 替换为等效的slice 对象:

    list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five']
    list_of_indexes = slice(1, 6, 2)
    
    res = list_of_items[list_of_indexes]
    

    物品获取器

    如果需要提供slice无法表示的列表,可以使用operator.itemgetter

    from operator import itemgetter
    
    list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five']
    list_of_indexes = [1, 3, 5]
    
    res = itemgetter(*list_of_indexes)(list_of_items)
    
    print(res)
    
    ('one', 'three', 'five')
    

    麻木

    第 3 方库 numpy 直接支持您所需的索引语法:

    import numpy as np
    
    list_of_items = ['zero', 'one', 'two', 'three', 'four', 'five']
    list_of_indexes = [1,3,5]
    
    res = np.array(list_of_items)[list_of_indexes].tolist()
    

    【讨论】:

    • 太棒了!谢谢! “切片”将成为我的 Python 词典中的新词。
    • 但是... 抱歉:list_of_indexes = slice(1, 6, 2) 不适合我,因为我有来自外部的索引列表。我不能用切片代替它。使用 Numpy 是可能的,但这太过分了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多