【问题标题】:Python: Only return matching values in up to three lists but ignore empty listsPython:只返回最多三个列表中的匹配值,但忽略空列表
【发布时间】:2020-01-21 07:22:52
【问题描述】:

我创建了三个整数列表(a、b 和 c),它们可能包含也可能不包含任何值。我想根据这些现有列表创建一个新列表(newList):

  • 如果所有三个列表都包含值,我想用每个列表共有的值填充 newList(例如 a = [1,2,3]、b = [2,3,4]、c = [ 3,4,5] 然后 newList = [3])
  • 如果所有列表都为空,我希望 newList 也为空(例如 a = []、b = []、c = [] 然后 newList = [])
  • 如果一个或两个列表为空,我想用非空列表共享的值填充 newList(例如 a = []、b = [2,3,4]、c = [3、 4,5] 然后 newList = [3,4]

我发现棘手的是,任何列表都可能是空的,也可能没有一个是空的,这意味着我目前不得不在不同的 if 语句中复制我的代码。

以下是我尝试过的,但看起来效率很低。

a = [1,2,3]
b = [2,3,4]
c = [3,4,5]

newList = []

if len(a) + len(b) + len(c) != 0:
    if len(a) > 0:
        if len(b) > 0:
            if len(c) > 0:
                #a, b and c all contain values, find common values
                newList = list(set(a) & set(b) & set(c))
            else:
                #a and b contain values, c is empty. Find common values in a and b.
                newList = list(set(a) & set(b))
        else:
            if len(c) > 0:
                #a and c contain values, b is empty. Find common values in a and c.
                newList = list(set(a) & set(c))
            else
                #only a contains values. b and c are empty.
                newList = a
    else:
        if len(b) > 0:
            if len(c) > 0:
                #b and c contain values, a is empty. Find common values in b and c.
                newList = list(set(b) & set(c))
            else:
                #only b contains values. a and c are empty
                newList = b
        else len(c > 0:
            #only c contains values. a and b are empty
            newList = c
else:
    #no lists contain values, leave newList as empty

如果有人有任何改进,我将不胜感激,在此先感谢。

【问题讨论】:

    标签: python list inner-join


    【解决方案1】:

    您可以这样处理它,泛化并使用集合:

    def inner_join_nonempty(*iterables):
        sets = (set(iterable) for iterable in iterables)
        nonempty_sets = [s for s in sets if s]
        return set.intersection(*nonempty_sets) if nonempty_sets else set()
    

    你的例子的用法:

    >>> inner_join_nonempty(a, b, c)
    {3}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多