Python 如何拉两条线?

Python 如何拉两条线?,python,python-2.7,Python,Python 2.7,我有两份清单: country_name = ['South Africa', 'India', 'United States'] country_code = ['ZA', 'IN', 'US'] zipped = zip(country_name, country_code) 我想将国家名称及其对应的代码组合在一起,然后执行排序操作以进行一些处理 当我试图压缩这两个列表时,我从这两个列表中获得第一个字符作为输出 我也试过这样做: for i in xrange(0,len(country

我有两份清单:

country_name = ['South Africa', 'India', 'United States']
country_code = ['ZA', 'IN', 'US']
zipped = zip(country_name, country_code)
我想将国家名称及其对应的代码组合在一起,然后执行排序操作以进行一些处理

当我试图压缩这两个列表时,我从这两个列表中获得第一个字符作为输出

我也试过这样做:

for i in xrange(0,len(country_code):
     zipped = zip(country_name[i][:],country_code[i][:])
     ccode.append(zipped)
把整个绳子拉上拉链,但没用。此外,我不确定在压缩2列表后,是否能够对结果列表进行排序。

您使用的
zip()
错误;将其与两个列表一起使用:

country_name = ['South Africa', 'India', 'United States']
country_code = ['ZA', 'IN', 'US']
zipped = zip(country_name, country_code)
您将其分别应用于每个国家/地区名称和国家/地区代码:

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

答案在你的问题中-使用:

如果列表长度不同,可以使用:

嗯,为什么不干脆用邮政编码(国家名称、国家代码)?
>>> 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)]