und*_*isp 3 python string extend
我试图将一个元素扩展到Python中的列表,但是,它不是在索引'i'中扩展字符串,而是扩展索引'i'中字符串的每个字符.
例如,我有一个名为'strings'的列表,只有一个字符串'string1'和一个名为'final_list'的空列表.
我想将'strings'的第一个元素扩展到'final_list',所以我这样做final_list.extend(strings[0]).但是,对应于插入的字符串,而不是以"长度为1"结尾的"final_list",列表最终的长度为7.
如果有帮助,这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
有谁知道我怎么能让它工作?
该extend方法将iterable作为参数,解包可迭代的内容,并将每个元素分别添加到调用它的列表中.在您的情况下,您正在"扩展"带有字符串的列表.字符串是可迭代的.因此,字符串被"解压缩",并且每个字符都单独添加:
>>> d = []
>>> d.extend('hello')
>>> print(d)
['h', 'e', 'l', 'l', 'o']
Run Code Online (Sandbox Code Playgroud)
如果您只想将列表的一个元素添加到另一个列表,请使用append.否则,在列表中包围字符串并重复扩展:
>>> d = []
>>> d.extend(['hello'])
>>> print(d)
['hello']
Run Code Online (Sandbox Code Playgroud)