【问题标题】:Combinde two lists of strings without getting tuples合并两个字符串列表而不获取元组
【发布时间】:2021-03-12 06:08:23
【问题描述】:

我有两个列表:

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

我的目标是压缩并加入他们,以便获得以下列表:

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

【问题讨论】:

  • countries = [" ".join(tpl) for tpl in zip(country_name, country_code)]

标签: python list join merge zip


【解决方案1】:

您可以将zip 与所谓的列表理解一起使用。

country_name = ['South Africa', 'India', 'United States']
country_code = ['ZA', 'IN', 'US']
countries = [' '.join(x) for x in zip(country_name, country_code)]
print(countries)

输出:

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

【讨论】:

  • 非常感谢。这似乎是最优雅的解决方案。由于计算时间对我来说不是那么重要,这是要走的路:-)
【解决方案2】:
countries = []

for i in range(0,len(country_name)):
    countries.append(country_name[i]+" "+country_code[i])

就这么简单

【讨论】:

  • 非常感谢。就计算时间而言,这似乎是最快的解决方案
【解决方案3】:

使用列表理解

country_name = ['South Africa', 'India', 'United States']
country_code = ['ZA', 'IN', 'US']
countries = [name + ' ' + code for name, code in zip(country_name, country_code)]

输出

>>> print(countries)
['South Africa ZA', 'India IN', 'United States US']

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 2021-08-14
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多