2015-04-29 59 views
1

我想在Python中擴展一個元素到列表中,但是,而不是在索引'i'中擴展字符串它擴展字符串的每個字符在索引'我'。Array.extend(字符串)添加每個字符,而不是隻字符串

例如,我有一個名爲'strings'的列表,只有一個字符串'string1'和一個名爲'final_list'的空列表。

我想將'strings'的第一個元素擴展到'final_list',所以我做了final_list.extend(strings[0])。但是,而不是「final_list」結束與長度1,對應插入該字符串時,列表結束了的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 

有誰知道我該如何使這個工作?

回答

4

extend方法需要一個可迭代作爲參數,解壓縮該可迭代地和單獨地將每個元件在其它被稱爲列表。在你的情況下,你是用一個字符串「擴展」一個列表。一個字符串是一個可迭代的。因此,該字符串爲「解包」,並且每個角色單獨加入:

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

如果你只是想列表中的一個元素添加到另一個列表,然後使用append。否則,在列表中圍繞字符串並重復擴展:

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

這實際上幫了很多,謝謝。 – undisp

0

嘗試之一:

final_list.extend([strings[0]]) 

或:

final_list.append(strings[0]) 
+0

append methos的工作原理。謝謝。 – undisp