2016-12-25 41 views
-4

如何添加两个列表,从而使结果列表保持其他列表完好:在python中,以这种方式添加两个列表:['a','b'] + ['c'] = [['a','b'],['c']。我该怎么做呢?

['5','6','7'] + ['1'] + ['9','7'] = [['5','6','7'], ['1'], ['9','7']] 

是否有可能做到这一点在Python?

当前代码:

def appendy(list_o_list): 
    temp_l = [] 
    for l in list_o_list: 
     temp_l.append(list(l)) 
     new_list=[] 
     new_list = [a + b for a, b in itertools.combinations(temp_l, 2)]      
     print("app",new_list) 
return (new_list) 

appendy([('g3', 'g1'), ('g3', 'g2')]) 
+2

这不是添加列表,而是将这些列表放入附加列表中。 – jonrsharpe

+0

你是不是要追加名单? –

+0

你是对的。我也希望把两个列表中的附加列表 –

回答

1

它不添加列表,它是附加列表。它很容易,只是做.append()

只要做到:

resulting_list = [] 
resulting_list.append(lista) 
resulting_list.append(listb) 
resulting_list.append(listc) 

所有原始名单将保持不变,并resulting_list将包含加入列表。你试图做的事情并不完全清楚。

+0

高清appendy(list_o_list): temp_l = [] 对于L在list_o_list: temp_l.append(表(1)) new_list = [] new_list = [A + b(对于a,b in itertools.combinations(temp_1,2)] print(“app”,new_list) return(new_list) appendy([('g3','g1'),('g3','g2 ')]) –

+3

@SatyamRaha为什么你会认为在评论中发布你的代码是任何方式合理的? –

+0

它有点凌乱...可能是你可以得到一些想法,我正在尝试做什么。 appendy从列表中找到所有可能的排列“list_o_list” –

0

+意味着对象的串联,所以直观:

[5, 6, 7] + [8, 9] 
= [5, 6, 7, 8, 9] 

正如Darkchili杀手提到的,你通过附加嵌入列出了另一份名单。事实上,一个相当简单的解决方法就是做:

Python 3.4.2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> a = [5, 6, 7] 
>>> b = [8, 9] 
>>> c = [] 
>>> c.append(a) 
>>> c.append(b) 
>>> c 
[[5, 6, 7], [8, 9]] 

如果你想获得幻想,你可以用做这样的事的特殊variable argument operator, *

>>> def join_l(*lists): 
...  temp = [] 
...  for l in lists: 
...   temp.append(l) 
...  return temp 
... 
>>> join_l([5, 6, 7], [8, 9]) 
[[5, 6, 7], [8, 9]] 

你甚至可以做到这太,并使它有点更容易阅读:

def join_l(*lists): 
...  return list(lists) 
... 
>>> join_l([5, 6, 7], [8, 9]) 
[[5, 6, 7], [8, 9]] 

最后,值得注意的是,有对列表的extend功能,附加在另一个列表中每个项目。你可以使用这个简化的第一个例子:

>>> a = [5, 6, 7] 
>>> b = [8, 9] 
>>> c = [] 
>>> c.extend([a, b]) 
>>> c 
[[5, 6, 7], [8, 9]] 

在这种情况下,因为输入的是完全一样的输出extend功能是不是非常有用。

相关问题