2016-09-08 38 views
1

我是新来的蟒蛇,我想通过以下方式来追加两个列表:追加和独特的:Python的

表1和表2的
list1=[2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2008, 2013, 2014] 

list2=['Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahrain', 'Guyana', 'Guyana'] 

长度总是在任何条件下相等。

I want the output to be : 
2006: [’Bahamas, The’] 
2007: [’Bahamas, The’] 
2008: [’Bahamas, The’, ’Bahrain’] 
2009: [’Bahamas, The’] 
2010: [’Bahamas, The’] 
2011: [’Bahamas, The’] 
2012: [’Bahamas, The’] 
2013: [’Bahamas, The’, ’Guyana’] 
2014: [’Bahamas, The’, ’Guyana’] 
+0

基于什么条件2008年,2013和2014有额外的价值? – AceLearn

回答

0

我认为你要查找的数据结构是一本字典。

使用这个数据结构,我们可以做到以下几点。

from collections import defaultdict 

创建一个新的defaultdict并通过它list

d = defaultdict(list) 

接下来我们需要zip这两个列表。 这是可以做到的:

zip(list1, list2) 

如果你正在使用Python 2,这将返回一个列表(伟大的,容易)。 但是,如果您使用的是Python 3,则会生成一个生成器(请参阅here)。所以,如果你正在使用Python 3(像我一样),看看这件事貌似可以发电机转换到一个列表如下:

这是这样的:

[(2006, 'Bahamas, The'), (2007, 'Bahamas, The'), (2008, 'Bahamas, The')...] 

现在我们所要做的就是通过这个对象遍历如下:

for k, v in zip(list1, list2): 
    d[k].append(v) 

因此,所有一起:

from collections import defaultdict 

d = defaultdict(list) 
for k, v in zip(list1, list2): 
    d[k].append(v) 

要查看可以使用的结果:

for k, v in d.items(): # iteritems if Python 2 
    print(k, v) 

这产生了:

2006 ['Bahamas, The'] 
2007 ['Bahamas, The'] 
2008 ['Bahamas, The', 'Bahrain'] 
2009 ['Bahamas, The'] 
2010 ['Bahamas, The'] 
2011 ['Bahamas, The'] 
2012 ['Bahamas, The'] 
2013 ['Bahamas, The', 'Guyana'] 
2014 ['Bahamas, The', 'Guyana'] 

仅供参考。

如果你真的喜欢一个列表,而不是一个字典,你可以使用:

list(d.items())  # Python 3 

list(d.iteritems()) # Python 2 
+0

非常感谢!它像魔术般运作! –