我定义了以下函数:
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)
测试时,它在第 15 行(上面的斜体字)返回以下错误:
File "/Users/ob/untitled0.py", line 15, in ma
AttributeError: 'NoneType' object has no attribute 'remove'
它如何不将 c 识别为列表?
a 和 b 是两个字符列表
先谢谢大家!
答案 0 :(得分:0)
list.remove() 将返回 None。如果你想从列表中删除元素,你可以使用索引或就地删除。
#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)
答案 1 :(得分:0)
我想我们的目标是获得两个列表中都没有出现的元素总数,你可以用更好更短的方式来做到这一点。
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