Array.extend(string) adds every character instead of just the string

痞子三分冷 提交于 2019-12-13 14:48:20

问题


I am trying to extend an element to a list in Python, however, instead of extending the string in the index 'i' it extends every character of the string in the index 'i'.

For example I have a list called 'strings' with just a string 'string1' and an empty list called 'final_list'.

I want to extend the first element of 'strings' to the 'final_list', so I do final_list.extend(strings[0]). But instead of the 'final_list' to end with a length of 1, corresponding to the string inserted, the list ends up with a length of 7.

If it helps, this is my code:

con = connect()
    i = 0
    new_files = []
    while i < len(files):
        info_file = obter_info(con, files[i])
        if info_file [5] == 0: #file not processed
            new_files.append(files[i])
        i += 1

Does anyone know how can I make this to work?


回答1:


The extend method takes an iterable as an argument, unpacks that iterable and adds each element individually to the list upon which it is called. In your case, you are "extending" a list with a string. A string is an iterable. As such, the string is "unpacked" and each character is added separately:

>>> d = []
>>> d.extend('hello')
>>> print(d)
['h', 'e', 'l', 'l', 'o']

If you simply want to add one element of a list to another list, then use append. Otherwise, surround the string in a list and repeat the extend:

>>> d = []
>>> d.extend(['hello'])
>>> print(d)
['hello']



回答2:


try that one:

final_list.extend([strings[0]])

or:

final_list.append(strings[0])


来源:https://stackoverflow.com/questions/29947007/array-extendstring-adds-every-character-instead-of-just-the-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!