简体   繁体   English

将两个列表的相应元素合并到新列表

[英]Merging corresponding elements of two lists to a new list

I have two lists as shown below,car_xy and car_id. 我有两个列表,如下所示,car_xy和car_id。 I have wrote a sample code to merge the corresponding elements of both lists, but am not getting the desired output. 我已经编写了一个示例代码来合并两个列表的相应元素,但未获得所需的输出。

car_xy =[(650,700),(568,231),(789,123),(968,369)]
car_id =[284,12,466,89]
#required_details merges the two lists
required_details = list(set(car_xy+car_id))
#now if i do print required_details the ouput will be a list like;
required_details = [284,12,(650,700),89,(568,231),466,(968,369),(789,123)] 
#the required details adds the information in list randomly. What if i want  the first elements of both the list together, like
required_details = [[284,(650,700)],[12,(568,231),[466,(789,123)],[89,(968,369)]]

Any suggestions will be great. 任何建议都会很棒。

实际上,您需要[list(pair) for pair in zip(car_id, car_xy)]

Assuming that the arrays are same length, you loop through them and combine them like this: 假设数组的长度相同,则循环遍历并像这样组合它们:

required_details = []
for i in range(len(car_xy)):
    required_details.append([car_id[i], car_xy[i]])

you are searching for the zip function. 您正在搜索zip功能。 https://docs.python.org/3/library/functions.html#zip https://docs.python.org/3/library/functions.html#zip

car_xy =[(650,700),(568,231),(789,123),(968,369)]
car_id =[284,12,466,89]
required_details = zip(car_id,car_xy)

Edit: adding the following makes it a list, in case there is a need for mutation. 编辑:添加以下内容使其成为列表,以防需要突变。

req_details_list = [list(pair) for pair in required_details]

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

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