[英]How to compare 1st element and operate 2nd element in 2D list in python
I have a 2D list (list of lists) in python in this format:我在 python 中有一个 2D 列表(列表列表),格式如下:
x=[[1,'A'],[1,'B'],[2,'A'],[3,'T'],[3,'Z'],[8,'K'],[6,'K'],[8,'N']]
I want to compare the first element that is integer and if the number is equal to another number in the list then combine their 2nd element ie alphabet.我想比较第一个整数元素,如果该数字等于列表中的另一个数字,则组合它们的第二个元素,即字母表。 Desired Output (List of strings):所需的输出(字符串列表):
["1:'A','B'","2:'A'","3:'T','Z'","8:'K',N'","6:'K'"]
I did try to use for loop but it is not checking the similarity of more than 2 elements.我确实尝试使用 for 循环,但它没有检查超过 2 个元素的相似性。 Is there any other simpler method for this?有没有其他更简单的方法呢?
My attempt:我的尝试:
for i in range(len(x)):
if x[i][0]==x[i+1][0]:
print x[i][-1]+","+x[i+1][-1]
else:
print x[i][-1]
You can construct your strings once you group your elements as you described, and for that you can use groupby :按照您的描述对元素进行分组后,您就可以构造字符串,为此您可以使用groupby :
from itertools import groupby
a = [[1,'A'],[1,'B'],[2,'A'],[3,'T'],[3,'Z'],[8,'K'],[6,'K'],[8,'N']]
{k: [v[1] for v in g] for k, g in groupby(sorted(a), key=lambda x: x[0])}
#{1: ['A', 'B'], 2: ['A'], 3: ['T', 'Z'], 6: ['K'], 8: ['K', 'N']}
From this, as of Python 3.6, you can do the following:从 Python 3.6 开始,您可以执行以下操作:
r = {k: [v[1] for v in g] for k, g in groupby(sorted(a), key=lambda x: x[0])}
result = ["{0}: {','.join(repr(i) for i in {1})}".format(k, v) for k, v in r.items()]
result
#["1: 'A','B'", "2: 'A'", "3: 'T','Z'", "6: 'K'", "8: 'K','N'"]
Using collections.defaultdict
使用collections.defaultdict
Ex:前任:
from collections import defaultdict
x=[[1,'A'],[1,'B'],[2,'A'],[3,'T'],[3,'Z'],[8,'K'],[6,'K'],[8,'N']]
result = defaultdict(list)
for k, v in x:
result[k].append(v)
result = ["{}: {}".format(k, ",".join(v)) for k,v in result.items()]
print(result)
Or using dict.setdefault
或者使用dict.setdefault
Ex:前任:
result = {}
for k, v in x:
result.setdefault(k, []).append(v)
Output:输出:
['8: K,N', '1: A,B', '2: A', '3: T,Z', '6: K']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.