如何串联2个过滤列表?

时间:2019-02-25 22:10:58

标签: python python-3.7

我假设过滤是引起问题的原因,但我可能是错的。我正在尝试连接两个列表,每个列表的数字都可以被3和5整除。以下是我的代码:

alist = list(range(1,100))
blist = list(range(600,700))

newListA = (filter(lambda x: x%3==0 and x%5==0, alist))
newListB = (filter(lambda x: x%3==0 and x%5==0, blist))
newListC = (list(newListA), list(newListB))

list(newListC)

3 个答案:

答案 0 :(得分:2)

有些错误。最主要的是您没有将列表连接起来,而是用括号创建了一个大小为2的tuple,第一个元素将是第一个列表,第二个元素是第二个列表。如果要使用tuple,请在方括号中使用lists。要连接两个列表,请使用运算符+

alist = list(range(1,100))
blist = list(range(600,700))
newListA = list(filter(lambda x: x%3==0 and x%5==0, alist))
newListB = list(filter(lambda x: x%3==0 and x%5==0, blist))
newListC = newListA + newListB
print(newListC)

答案 1 :(得分:1)

您可以简单地使用内置的extend功能。 Refer to Python docs.

>>> alist = list(range(1,100))

>>> blist = list(range(600,700))

>>> newListA = list(filter(lambda x: x%3==0 and x%5==0, alist))

>>> newListB = list(filter(lambda x: x%3==0 and x%5==0, blist))

>>> print(newListA.extend(newListB))

答案 2 :(得分:0)

总而言之,@Rushiraj Nenuji@JosepJoestar都是正确的。有两种连接列表的方法。

一个是old_list.extend(new_list),它将new_list并连接old_list

使用这种方法,您的代码可能是

alist = list(range(1,100))
blist = list(range(600,700))

newListA = list(filter(lambda x: x%3==0 and x%5==0, alist))
newListB = list(filter(lambda x: x%3==0 and x%5==0, blist))
newListC = list()
newListC.extend(newListA)
newListC.extend(newListB)
# newListC is now the concatenation of newListA and newListB

另一种方法是仅使用+符号。因此,list1 + list2将返回一个将list1list2串联在一起的值。

使用这种方法,您的代码可能是

alist = list(range(1,100))
blist = list(range(600,700))

newListA = list(filter(lambda x: x%3==0 and x%5==0, alist))
newListB = list(filter(lambda x: x%3==0 and x%5==0, blist))
newListC = newListA + newListB
# newListC is now the concatenation of newListA and newListB