[英]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.