简体   繁体   English

如何水平合并两个列表

[英]How to merge two lists horizontally

EDIT: I am using zip, but as my environment is in Python 2.x the zip code is matching character by character instead of items in list 1 with items in list 2编辑:我正在使用 zip,但由于我的环境在 Python 2.x 中,邮政编码逐字符匹配,而不是列表 1 中的项目与列表 2 中的项目

I am trying to merge two lists horizontally.我正在尝试水平合并两个列表。 My sample dataset is something like this:我的示例数据集是这样的:

test_list1 = ['1', '4', '5', '6', '5'] 
test_list2 = ['a','b','c','d','e']

I want the outcome of the combined list to look like this:我希望组合列表的结果如下所示:

Combined_list = ['1a', '4b', '5c', '6d', '5e']

您可以使用 zip:

[f"{x[0]}{x[1]}" for x in zip(test_list1, test_list2)]

You can use zip to iterate through two lists in parallel您可以使用 zip 并行遍历两个列表

test_list1 = ['1', '4', '5', '6', '5'] 
test_list2 = ['a','b','c','d','e']

Combined_list = [f_item + s_item for f_item, s_item in zip(test_list1, test_list2)]

By using zip and join :通过使用zipjoin

test_list1 = ['1', '4', '5', '6', '5'] 
test_list2 = ['a','b','c','d','e']

[''.join(t) for t in zip(test_list1, test_list2)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM