如何压缩两个字符串?

2024-09-30 04:31:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个清单:

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


Tags: namein列表排序code国家countryunited
2条回答

答案在您的问题中-使用^{}

>>> 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')]

如果列表的长度不同,可以使用^{}

>>> 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)]

您使用的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')]

相关问题 更多 >

    热门问题