简体   繁体   English

从两个列表中提取一个公共元素,并创建一个字典,通过避免重复从一个列表映射到另一个列表

[英]Extract one common element from two lists and create a dictionary with mapping from one list to other by avoiding duplicates

I am trying to extract same values from one position of a nested list and its corresponding values from another position.我正在尝试从嵌套列表的一个 position 中提取相同的值,并从另一个 position 中提取相应的值。

JJ = [['HC', 0, ' 3.6'], 
      ['HC', 1, ' 3.9'], 
      ['HC', 2, ' 7.0'], 
      ['NC', 7, ' 0.3'], 
      ['NC', 8, ' 0.4'], 
      ['NC', 9, ' 0.5'], 
      ['NC', 10, ' 0.6'], 
      ['NC', 11, ' 0.7'], 
      ['DC', 12, ' 0.8'], 
      [['DC','NC'], 13, ' 0.9']]

This is a list where the first element is repeated in some of the sub-lists.这是一个列表,其中第一个元素在某些子列表中重复。 I am trying to write a code which will take all the third elements from each of the sub-list and map it with its corresponding first element using two lists.我正在尝试编写一个代码,它将使用两个列表从每个子列表和 map 中获取所有第三个元素及其对应的第一个元素。 Ignore the second element.忽略第二个元素。 The required output is supposed to be:所需的 output 应该是:

list1 = [['HC'],['NC'],['DC'],['DC','NC']]
list2 = [[3.6, 3.9, 7], [0.3, 0.4, 0.5, 0.6, 0.7],[0.8],[0.9]]

where each element in list1 now corresponds to the element of the same position in list2 , or can be a dictionary mapping.其中list1中的每个元素现在对应于list2中相同 position 的元素,或者可以是字典映射。 I have tried this:我试过这个:

list1 = []
list2 = []
for i in range(0,len(JJ)-1):
    #i_set = set(i)
    #for j in range(len(i)):
    if JJ[i][0] == JJ[i+1][0]:
        list1.append(JJ[i][0])
        list2.append(JJ[i][2])
list1 = set(list1)

This gives me same elements again and again in list1 and if I convert it to a set, the mapping/correspondence between elements is lost.这在list1中一次又一次地给我相同的元素,如果我将它转换为一个集合,元素之间的映射/对应就会丢失。 Also, since the last element is len(JJ)-1 (without subtracting 1 the code shows index error), I cannot collect the last element.此外,由于最后一个元素是len(JJ)-1 (不减去 1,代码显示索引错误),我无法收集最后一个元素。 Is there any other way to do this?还有其他方法吗?

With a simple for-loop: The basic idea is to keep track of the previous first element and the current first element and if it differs, append a new list to list1 and list2 .使用简单的 for 循环:基本思想是跟踪前一个第一个元素和当前第一个元素,如果不同,则 append 一个新列表到list1list2

list1 = []
list2 = []
prev = curr = None
for sublist in JJ:
    curr = sublist[0]
    if curr != prev:
        list1.append([curr])
        list2.append([])
    list2[-1].append(float(sublist[2]))
    prev = curr

groupby from the itertools module could be useful itertools模块中的groupby可能很有用

from itertools import groupby

JJ = [['HC', 0, ' 3.6'], ['HC', 1, ' 3.9'], ['HC', 2, ' 7.0'], ['NC', 7, ' 0.3'], 
      ['NC', 8, ' 0.4'], ['NC', 9, ' 0.5'], ['NC', 10, ' 0.6'], ['NC', 11, ' 0.7'], 
      ['DC', 12, ' 0.8'], [['DC','NC'], 13, ' 0.9']]

list1, list2 = [], []
#  groupby the first elements in the inner lists
for key, group in groupby(JJ, lambda x: x[0]):
    # append keys as lists
    list1.append(key if isinstance(key, list) else [key])
    # append the last element of the sublists
    list2.append([float(e[-1]) for e in group])

print(list1)
# [['HC'], ['NC'], ['DC'], ['DC', 'NC']]

print(list2)
# [[3.6, 3.9, 7.0], [0.3, 0.4, 0.5, 0.6, 0.7], [0.8], [0.9]]

You can do it like this without any additional imports:您可以这样做而无需任何其他导入:

JJ = [['HC', 0, ' 3.6'], 
      ['HC', 1, ' 3.9'], 
      ['HC', 2, ' 7.0'], 
      ['NC', 7, ' 0.3'], 
      ['NC', 8, ' 0.4'], 
      ['NC', 9, ' 0.5'], 
      ['NC', 10, ' 0.6'], 
      ['NC', 11, ' 0.7'], 
      ['DC', 12, ' 0.8'], 
      [['DC','NC'], 13, ' 0.9']]

dict_ = {}

for k, _, n in JJ:
    if isinstance(k, list):
        k = tuple(k)
    dict_.setdefault(k, []).append(float(n))

list1 = []
list2 = []


for k, v in dict_.items():
    if isinstance(k, tuple):
        k = list(k)
    list1.append(k)
    list2.append(v)

print(list1)
print(list2)

Output: Output:

['HC', 'NC', 'DC', ['DC', 'NC']]
[[3.6, 3.9, 7.0], [0.3, 0.4, 0.5, 0.6, 0.7], [0.8], [0.9]]

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

相关问题 如何从两个列表创建字典,一个列表是键,另一个包含嵌套值? - How can I create a dictionary from two lists, one list is the keys, the other contains nested values? 创建一个列表,其中每个元素只有一次来自 Python 中其他两个列表的元素 - Create a list which has only one time each element from two other lists in Python 从一个Python列表中删除重复项,并基于此修剪其他列表 - Remove duplicates from one Python list, prune other lists based on it 从python中的一个列表创建两个列表? - Create two lists from one list in python? 当存在重复项时,如何将两个元素列表转换为字典(一个元素是键,另一个是值)? - How to convert a two element list into dictionary (one element will be key and other will be value), when duplicates are present? 从单行中的两个列表创建字典 - Create a dictionary from two lists in a one-liner 从一本字典中提取两本字典 - Extract two dictionary from one dictionary 从 pandas 列中的一个元素的列表中提取字典值 - Extract dictionary value from a list with one element in a pandas column 根据另一个列表中的常见值从一个列表中获取值列表的字典 - Get a dictionary of lists of values from one list based on common values from another list 从其他列表创建一个新的字典列表? - Create a new dictionary list from other lists?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM