Python 如何连接2个过滤列表?
我假设过滤是导致问题的原因,但我可能错了。我试图连接两个列表,每个列表中的数字可以被3和5整除。下面是我的代码:Python 如何连接2个过滤列表?,python,python-3.7,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(newList
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)
有些事情不对劲。主要的一点是,您没有连接列表,使用括号创建了一个大小为2的
元组
,第一个元素是第一个列表,第二个元素是第二个列表。使用括号的地方都是元组
,如果需要列表
请使用方括号。要连接两个列表,请使用运算符+
alist=list(范围(1100))
blist=列表(范围(600700))
newListA=list(筛选器(lambda x:x%3==0和x%5==0,列表))
newListB=list(筛选器(lambda x:x%3==0和x%5==0,blist))
newListC=newListA+newListB
打印(newListC)
您只需使用内置的扩展功能即可
总结和澄清,两者都是正确的。有两种连接列表的方法
一种是old\u list.extend(new\u list)
,它接受new\u list
并将old\u 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
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
另一种方法是只使用+
符号。因此,list1+list2
将返回一个连接list1
和list2
的值
使用此方法,您的代码可以
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
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
@Savaria预期的行为描述得很清楚。如果您搜索短语“Python列表连接”,您会找到比我们在这里的答案更好的资源来解释它。My bad,将删除注释。可能与Great重复,谢谢!我第一次发帖,你可以告诉我,我对这个很陌生,所以我真的很感谢你的帮助谢谢你的帮助!