2013-07-30 37 views
4

我有兩個列表:如何壓縮兩個字符串?

country_name = ['South Africa', 'India', 'United States'] 
country_code = ['ZA', 'IN', 'US'] 

我想組的國家名稱和相應的代碼放在一起,然後進行排序操作做一些處理

當我試圖壓縮這兩個名單,我我從兩個列表中獲取第一個字符作爲輸出。

我也試着這樣做:

for i in xrange(0,len(country_code): 
    zipped = zip(country_name[i][:],country_code[i][:]) 
    ccode.append(zipped) 

來壓縮整個字符串,但沒有奏效。另外我不確定在壓縮2列表後,我將能夠對結果列表進行排序或不排序。

+4

呃,爲什麼不只是'zip(country_name,country_code)'? – nneonneo

回答

4

答案就在你的問題 - 使用zip

>>> country_name = ['South Africa', 'India', 'United States'] 
>>> country_code = ['ZA', 'IN', 'US'] 
>>> zip(country_name, country_code) 
[('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US')] 

如果你有不同長度的列表,你可以使用itertools.izip_longest

>>> from itertools import izip_longest 
>>> country_name = ['South Africa', 'India', 'United States', 'Netherlands'] 
>>> country_code = ['ZA', 'IN', 'US'] 
>>> list(izip_longest(country_name, country_code)) 
[('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US'), ('Netherlands', None)] 
7

您正在使用zip()錯誤;與兩個列表使用它:

zipped = zip(country_name, country_code) 

你把它應用到每一個國家的名稱和國家代碼單獨

>>> zip('South Africa', 'ZA') 
[('S', 'Z'), ('o', 'A')] 

zip()組合兩個輸入由配對關每個元素序列;在字符串中,單個字符是序列的元素。由於國家代碼中只有兩個字符,因此最後會列出兩個元素的列表,每個元素都是配對字符的元組。

一旦這兩個列表合併成一個新的,你可以肯定那種列表,第一或第二元素:

>>> zip(country_name, country_code) 
[('South Africa', 'ZA'), ('India', 'IN'), ('United States', 'US')] 
>>> sorted(zip(country_name, country_code)) 
[('India', 'IN'), ('South Africa', 'ZA'), ('United States', 'US')] 
>>> from operator import itemgetter 
>>> sorted(zip(country_name, country_code), key=itemgetter(1)) 
[('India', 'IN'), ('United States', 'US'), ('South Africa', 'ZA')]