如何压缩两个字符串?

时间:2013-07-30 07:32:13

标签: python python-2.7

我有两个清单:

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列表后,我将能够对结果列表进行排序。

2 个答案:

答案 0 :(得分: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')]

答案 1 :(得分: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)]