我对为修改作为输入的列表而编写的两个函数的行为感到有点困惑。在我看来,两者都应该做同样的事情,但事实并非如此。看看:
def headerFormat1(list1):
char_to_remove = ['(', ')']
list2 = list1[:]
list1 = []
for headers in list2:
headers = headers.replace(' ', '_')
for character in char_to_remove:
headers = headers.replace(character, '')
list1.append(headers)
del list2
return list1
def headerFormat2(list1):
char_to_remove = ['(', ')']
for i, headers in enumerate(list1):
list1[i] = headers.replace(' ', '_')
for character in char_to_remove:
list1[i] = headers.replace(character, '')
return list1
theList = ['I want Underscores Instead', 'R(e(m(o(v(e()P)a)r)e)n)t)h)e)s)e)s', 'LetMeBe']
print(headerFormat1(theList)) #prints: ['I_want_Underscores_Instead', 'RemoveParentheses', 'LetMeBe']
print(headerFormat2(theList)) #prints: ['I want Underscores Instead', 'R(e(m(o(v(e(Parentheses', 'LetMeBe']
我的意思是好的,第一个工作,因为它应该是altough我发现列表重复冗余,可能没有必要\ overkill(?)
但是第二个......除去括号后的奇怪之处是什么?此外,即使它不能正常工作,它也表明可以就地修改列表元素(删除')然后为什么不替换空格?
感谢。
答案 0 :(得分:1)
您每次使用原始标题更改list1 [i] 检查以下代码是否有效
def headerFormat1(list1):
char_to_remove = ['(', ')']
list2 = list1[:]
list1 = []
for headers in list2:
headers = headers.replace(' ', '_')
for character in char_to_remove:
headers = headers.replace(character, '')
list1.append(headers)
del list2
return list1
def headerFormat2(list1):
char_to_remove = ['(', ')']
for i, headers in enumerate(list1):
headers = headers.replace(' ', '_')
for character in char_to_remove:
headers = headers.replace(character, '')
list1[i]=headers
return list1
theList = ['I want Underscores Instead', 'R(e(m(o(v(e()P)a)r)e)n)t)h)e)s)e)s', 'LetMeBe']
print(headerFormat1(theList))
print(headerFormat2(theList))