简体   繁体   English

如何在python中的2D列表中比较第一个元素并操作第二个元素

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

相关问题 比较2D列表的第一个元素并在第二个元素上进行操作 - Compare 1st element of a 2D list and operate on 2nd element 查找2d数组元素的第一元素和第二元素之间的最大和最小差异 - Finding biggest and smallest difference between 1st and 2nd element of 2d array elements Python:如果列表中的第一个元素重复并且第二个元素在列表系列中最低,则删除列表中的列表 - Python: delete list in list if 1st element in list is duplicated and 2nd element is lowest in lists series 如何首先使用第一列以升序对二维列表进行排序,然后在 python 中以降序对第二列进行排序? - How to sort a 2D list first using 1st column in increasing order, then by 2nd column in decreasing order in python? 无法获取列表的第一个和第二个元素 - 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 如何对列表列表进行排序并按间隔仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements by intervals? 如何对列表列表进行排序并仅保留每个第一个元素的最大第二个元素? - How to sort a list of lists and and to keep only the maximal 2nd element of each of the 1st elements? 给定两个二维点列表,如何为第一个列表中的每个点找到第二个列表中最近的点? - Given two lists of 2d points, how to find the closest point in the 2nd list for every point in the 1st list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM