python - 过滤复杂列表中的元素

标签 python list dictionary

我有这个数据框

df1 = [('f', {'abe': 1}), ('f', {'tbeli': 1}), ('g', {'mos': 1}), ('g', {'esc': 1})]

我想要这样

df2=[('f', {'abe': 1}), ('f', {'tbeli': 1})]

df3=[('g', {'mos': 1}), ('g', {'esc': 1})]

我尝试了这段代码

L1 = [year for (title, year) in (sorted(df1.items(), key=lambda t: t[0]))]

最佳答案

过滤列表的一种方法是将其拆分为由“f”或“g”索引的子列表:

from collections import defaultdict

df1 = [('f', {'abe': 1}), ('f', {'tbeli': 1}), ('g', {'mos': 1}), ('g', {'esc': 1})]

df = defaultdict(list)

for item in df1:
    df[item[0]].append(item)

df2 = df['f']
df3 = df['g']

print(df2)
print(df3)

输出:

[('f', {'abe': 1}), ('f', {'tbeli': 1})]
[('g', {'mos': 1}), ('g', {'esc': 1})]

关于python - 过滤复杂列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49873160/

相关文章:

Python:带参数的队列方法 wait_for 谓词

python - 这个python程序有什么错误?

Python字典: If the keys are the same multiply the values

java - 如何以 Java 8 方式将具有属性的列表转换为另一个列表?

c - 跳鱼词典

python - boto.ec2.connection.EC2Connection.request_spot_instances() 不返回 boto.ec2.spotinstancerequest.SpotInstanceRequest

c - 链表基本内存(C语言)

c# - 数组索引器签名返回对象 - 它是否装箱?

java - 为什么字典初始化时不会发生内存溢出?

c++ - 从 3D map 中插入和读取值