'append()'和没有方括号的list元素之间的区别

时间:2014-09-22 03:02:13

标签: python

指令: get_name_list()函数返回参数中所有名称的列表:name_list,参数中提供给定的字母:to_look_for。

问题:如果我删除'a_list + = [name]'表达式中'name'的方括号,它将显示以下错误输出。但是,如果使用方括号或'append()'方法,将生成正确的输出(下面的第二个正确输出)。我想知道为什么没有[name]中的方括号,没有产生正确的输出?

输出错误:

names with d ['J', 'a', 'd', 'e']
names with k ['M', 'i', 'k', 'e', 'y']

代码错误:

def main():
    names = ["Jasper", "Jade", "Mikey", "Giani"]
    names_d = get_name_list(names, "d")
    names_k = get_name_list(names, "k")
    print("names with d", names_d)
    print("names with k", names_k)

    def get_name_list(name_list, to_look_for):

        a_list = [] 
        for name in name_list:
            #print(name)
            if to_look_for in name:
                print(name)
                a_list += name
                #a_list.append(name)

        return a_list

    main()

正确输出

names with d ['Jade']
names with k ['Mikey']

正确的代码:

def main():
    names = ["Jasper", "Jade", "Mikey", "Giani"]
    names_d = get_name_list(names, "d")
    names_k = get_name_list(names, "k")
    print("names with d", names_d)
    print("names with k", names_k)    

def get_name_list(name_list, to_look_for):

    a_list = [] 
    for name in name_list:
        #print(name)
        if to_look_for in name:
            print(name)
            #a_list += name
            a_list.append(name)

    return a_list

main()

1 个答案:

答案 0 :(得分:3)

'+ ='操作等于列表内置方法的extend()。它会先将值改为等号,然后再进行扩展。

在你的情况下:

a_list += name  # which is the same as a_list.extend(name), although name is a string, it will be converted to a list first

当字符串转换为列表时,它的作用就像将'abc'更改为['a', 'b', 'c']一样。这就是您的['J', 'a', 'd', 'e']来自

的地方