[英]How to detect different elements in list and create new lists from them (finding) with python
To send an e-mail element by element I need to first detect different elements in list and then create new lists from them. 要按元素发送电子邮件元素,我需要首先检测列表中的不同元素,然后根据它们创建新列表。
Does anyone can help me about the problem below ? 有谁能帮助我解决以下问题?
The list that I mentioned is also interrelated with another one. 我提到的列表也与另一个列表相互关联。
I have: 我有:
list_I = [123, 453, 444, 555, 567, ...]
list_II = [A , A, B, C, B, ....]
What I hope to get is: 我希望得到的是:
New_list_I = [123, 453]
New_list_I_a = [A, A]
New_list_II = [444,567]
New_list_II_a = [B, B]
New_list_III = [555]
New_list_III_a = [C]
One way would be to create a dictionary from the two lists: 一种方法是从两个列表创建字典:
from collections import defaultdict
d = defaultdict(list)
for k,v in zip(list_2, list_1):
d[k].append(v)
# defaultdict(list, {'A': [123, 453], 'B': [444, 567], 'C': [555]})
And then obtain the specified output from the dictionary using a list comprehension. 然后使用列表推导从字典中获取指定的输出。
[[[k for _ in range(len(v))], v] for k,v in d.items()]
# [[['A', 'A'], [123, 453]], [['B', 'B'], [444, 567]], [['C'], [555]]]
Note that a nested list structure is much easier to handle and to work with than rather a series of lists created dynamically. 请注意,嵌套的列表结构比动态创建的一系列列表更易于处理和使用。 Note that from this result you can select each resulting sublist using Basic Slicing and Indexing
请注意,您可以从此结果中使用“ 基本切片和索引”选择每个结果子列表
Why not just create a dict out of those two lists with a key,value and then sort on the basis of value: 为什么不只用键,值从这两个列表中创建一个字典,然后根据值排序:
list_I = [123, 453, 444, 555, 567]
list_II = ['A' , 'A', 'B', 'C', 'B']
res = dict(zip(list_I, list_II))
print(sorted(res.items(), key=lambda x:x[1]))
OUTPUT : 输出 :
[(123, 'A'), (453, 'A'), (444, 'B'), (567, 'B'), (555, 'C')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.