简体   繁体   English

比较2D列表的第一个元素并在第二个元素上进行操作

[英]Compare 1st element of a 2D list and operate on 2nd element

I've a 2D list of numbers in this format: 我有以下格式的2D数字列表:

[['1.1','5000'],['2.1','5003',['3.4','5007'],['3.4','5008'],['8.7','5050'],['21.2','6000'],['21.2','6001'],['99.1','5009']]

I want the output in the format: 我想要以下格式的输出:

1.1 5000
2.1 5003
3.4 5007,5008
8.7 5050
21.2 6000,6001
99.1 5009

The objective is to compare if the same number is coming in the 1st element of a 2D list, if it is same then print its content in the same line using ',' 目的是比较2D列表的第一个元素中是否有相同的数字,如果相同,则使用','在同一行中打印其内容

My attempt: 我的尝试:

from collections import defaultdict
x=[['1','5000'],['2','5003',['3','5007'],['3','5008'],['8','5050'],['21','6000'],['21','6001'],['99','5009']]
result=defaultdict(list)
for k,v in x:
 result[k].append(v)
result=["{}\t{}\r\n".format(k,",".join(v)) for k,v in result.items()]
print "".join(result)

The problem in my code that it does not come in order. 我的代码中的问题是顺序不正确。 I provided a sorted list but the output is coming in random order. 我提供了一个排序列表,但是输出以随机顺序出现。 I want to perform operation as it is. 我想按原样执行操作。

from collections import OrderedDict
x=[['1','5000'],['2','5003'],['3','5007'],['3','5008'],['8','5050'],['21','6000'],['21','6001'],['99','5009']]
result = OrderedDict()
for k,v in x:
    if k in result.keys():
        result[k].append(v)
    else:
        result[k] = [v]
res=["{}\t{}\r\n".format(k,",".join(v)) for k,v in result.items()]
print "".join(res)

暂无
暂无

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

相关问题 如何在python中的2D列表中比较第一个元素并操作第二个元素 - How to compare 1st element and operate 2nd element in 2D list in python 查找2d数组元素的第一元素和第二元素之间的最大和最小差异 - Finding biggest and smallest difference between 1st and 2nd element of 2d array elements 无法获取列表的第一个和第二个元素 - Cannot get 1st and 2nd element of a list 从列表列表中删除第一个元素,然后是第一个和第二个元素[保留] - Removing the 1st element then 1st and 2nd element from a list of lists [on hold] for循环跳过第一和第二元素 - for loop skipping 1st and 2nd element Python:如果列表中的第一个元素重复并且第二个元素在列表系列中最低,则删除列表中的列表 - Python: delete list in list if 1st element in list is duplicated and 2nd element is lowest in lists series 首先按第 1 列然后按第 2 列对 2D 列表进行排序 - sort a 2D list first by 1st column and then by 2nd column 通过一个元组的第一个元素和另一个元组的第二个元素相等来排序元组列表 - Ordering a list of tuples by equality of the 1st element of one tuple and the 2nd element of another tuple 循环遍历两个列表以查找第一个列表中的元素是否存在于第二个列表中 - loop through two lists to find if an element from 1st list exists in the 2nd list 如何对列表列表进行排序并按间隔仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements by intervals?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM