循环在第一次迭代时卡住了

时间:2016-05-30 17:21:27

标签: python list if-statement for-loop web-crawler

在尝试创建网络抓取工具时,我尝试定义此功能:

#a and b are lists.
def union(a, b):
    i = 0
    while i <= len(b):
        if b[i] in a :
            a = a.append(b[i])   
        i = i + 1    
    return a

然后测试它,我输入:

a = [1,2,3]
b = [2,4,6,9]
union(a,b)

它一直给我错误

TypeError: argument of type 'NoneType' is not iterable

通过将我的条件编辑到if a and b[i] not in a:,我在另一个线程中看到了这个问题的解决方案,但是在测试时,只有解决它才会将b的1个元素追加到a,然后停止工作。

1 个答案:

答案 0 :(得分:0)

请参阅下面的更新和评论代码

#a and b are lists.
def union(a, b):
    i = 0
    while i <= len(b):
        if b[i] in a :
            # the problem lies here. append returns None
            # a = a.append(b[i])
            # this should work
            a.append(b[i])   
        i = i + 1    
    return a