实际上,我编写了一个代码以从列表中查找字符并打印索引,但仍无法理解这两个代码之间的区别,请帮帮我:
#My list:
l = ["MA-%78*%%1","MA%-78*%1","MA%%-%78*1","M%A#-78*%%1"]
search(l,"%")
代码1:
def search(string_list,search_character):
sl = string_list
char1 = search_character
l1 = list()
l11 = list()
for j in range(len(string_list)):
l1.clear()
s1 = string_list[j]
for i in range(len(s1)):
if s1[i] == search_character:
l1.append(i+1)
l11.append(l1)
return l11
这将产生输出:
[[1, 8, 9], [1, 8, 9], [1, 8, 9], [1, 8, 9]]
代码2:
def search(string_list,search_character):
sl = string_list
char1 = search_character
l11 = list()
for j in range(len(string_list)):
l1 = list()
s1 = string_list[j]
for i in range(len(s1)):
if s1[i] == search_character:
l1.append(i+1)
l11.append(l1)
return l11
当我再次初始化列表而不清除它时,我得到正确的输出:
[[4, 8, 9], [3, 8], [3, 4, 6], [2, 9, 10]]
我不了解l1.clear()
函数出了什么问题。
答案 0 :(得分:0)