【问题标题】:How to zip two strings? [duplicate]如何压缩两个字符串? [复制]
【发布时间】:2013-07-30 05:42:06
【问题描述】:

我有两个列表:

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

【问题讨论】:

  • 呃,为什么不直接zip(country_name, country_code)

标签: python python-2.7


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    答案在您的问题中 - 使用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)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多