Array.extend(string)添加每个字符,而不只是字符串 [英] Array.extend(string) adds every character instead of just the string

查看:95
本文介绍了Array.extend(string)添加每个字符,而不只是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将元素扩展到Python中的列表,但是,没有扩展索引"i"中的字符串,而是扩展了索引"i"中字符串的每个字符.

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'.

例如,我有一个名为字符串"的列表,其中只有一个字符串"string1"和一个空列表,名为"final_list".

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

我想将'strings'的第一个元素扩展到'final_list',所以我要做final_list.extend(strings[0]).但是,列表的最后长度为7,而不是"final_list"的长度为1(与插入的字符串相对应).

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?

推荐答案

extend方法以Iterable作为参数,解包该Iterable并将每个元素分别添加到调用它的列表中.在您的情况下,您正在扩展"一个带有字符串的列表.字符串是可迭代的.这样,该字符串是解压"的,并且每个字符分别添加:

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']

如果只想将列表的一个元素添加到另一个列表,请使用append.否则,将字符串括在列表中并重复扩展:

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']

这篇关于Array.extend(string)添加每个字符,而不只是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆