简体   繁体   English

引用列表时出现“NoneType”错误

[英]'NoneType' Error when referring to a list

I define the below function:我定义了下面的 function:

def makeAnagram(a, b):
    c = list(a)
    d = list(b)
    x = 0
    for i in c:
        if i not in d:
            c = c.remove(i)
            x += 1
    for i in d:
        if i not in c:
            d = d.remove(i)
            x += 1
    return int(x)

When tested, it returns in line 15 (in italics above) the below error:测试时,它在第 15 行(上面的斜体)返回以下错误:

  File "/Users/ob/untitled0.py", line 15, in ma

AttributeError: 'NoneType' object has no attribute 'remove'

How it doesn't recognise c as a list?它如何不将 c 识别为列表?

a and b are meant to be two list of characters a 和 b 是两个字符列表

Thank you in advance to everybody!提前感谢大家!

list.remove() will return None. list.remove() 将返回无。 if you wanna delete element from the list you can use index or do in place remove.如果你想从列表中删除元素,你可以使用索引或就地删除。

#inplace remove
def makeAnagram(a, b):
    c = list(a)
    d = list(b)
    x = 0
    for i in c:
        if i not in d:
            c.remove(i)
            x += 1
    for i in d:
        if i not in c:
            d.remove(i)
            x += 1
    return int(x)


makeAnagram([5, 9], [6, 0])

# using index
def makeAnagram(a, b):
    c = list(a)
    d = list(b)
    x = 0
    for i in c:
        if index,i not in enumerate(d):
            del c[index]
            x += 1
    for index,i in enumerate(d):
        if i not in c:
            del d[index]
            x += 1
    return int(x)

I guess the goal is to get the total number of elements which don't occur in both lists, you can do this in a better and shorter way.我想目标是获得两个列表中都没有出现的元素总数,您可以以更好和更短的方式做到这一点。

c = ['a','b','e','d']
d = ['w','b','c','d']

c_not_d = len(set(c).difference(set(d)))
# Output of above without len(), will be {'a', 'e'}

d_not_c = len(set(d).difference(set(c)))
# Output of above without len(), will be {'w', 'c'}

# Total Count required
total_count = c_not_d + d_not_c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM