【问题标题】:Python 3.4: adding value to list if condition existsPython 3.4:如果条件存在,则向列表添加值
【发布时间】:2015-06-02 12:02:26
【问题描述】:

我有这样一个场景:

mainList = [[9,5],[17,3],[23,1],[9,2]]
secondaryList = [9,12,28,23,1,6,95]
myNewList = []

myNewList.append([[a,b] for a,b in mainList if a in secondaryList])

这个,把我还给我:

myNewList = [[9,5],[23,1],[9,2]]

但我只需要“a”的第一次出现。换句话说,我需要获得:

myNewList = [[9,5],[23,1]]

我怎样才能做到这一点?

【问题讨论】:

    标签: list python-3.x append


    【解决方案1】:

    首先:

    myNewList = []
    myNewList.append([[a,b] for a,b in mainList if a in secondaryList])
    

    简单来说就是

    myNewList = [[a,b] for a,b in mainList if a in secondaryList]
    

    然后: 您正在构建的功能是一个 python 字典。您在mainList 中的二元列表与dict.items() 相同!

    所以你要做的是从mainList 中构建一个dict(反过来,因为通常你只保存last,而不是first em> 发生):

    mainDict = dict([reversed(mainList)])
    

    然后您只需制作新列表:

    myNewList = [ (key, mainDict[key]) for key in secondaryList ]
    

    【讨论】:

    • 对我不起作用:mainDict = dict([reversed(secondaryList)]) ValueError: 字典更新序列元素 #0 的长度为 7; 2 是必需的
    【解决方案2】:

    您可以使用集合来存储第一个元素,然后在添加子列表之前检查是否存在第一个元素:

    >>> seen=set()
    >>> l=[]
    >>> for i,j in mainList:
    ...    if i in secondaryList and i not in seen:
    ...        seen.add(i)
    ...        l.append([i,j])
    ... 
    >>> l
    [[9, 5], [23, 1]]
    

    或者您可以使用collections.defaultdictdeque 并指定其maxlen。但请注意,如果您想要a 的第一次出现,则需要从头到尾循环列表,因为deque 将保留最后一个插入值:

    >>> from collections import defaultdict
    >>> from functools import partial
    
    >>> d=defaultdict(partial(deque, maxlen=1))
    >>> for i,j in mainList[::-1]:
    ...    if i in secondaryList:
    ...       d[i].append(j)
    ... 
    >>> d
    defaultdict(<functools.partial object at 0x7ff672706e68>, {9: deque([5], maxlen=1), 23: deque([1], maxlen=1)})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-12
      • 2014-07-09
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多