根据唯一值将列表拆分为两个列表 [英] splitting a list into two lists based on a unique value

查看:43
本文介绍了根据唯一值将列表拆分为两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的文本文件:

I have a text file that looks something like this:

hello 12
hello 56
world 25
world 26

python 中是否有一种方法可以解析我从读取此数据中获得的列表以获得两个单独的嵌套列表(或一个 numpy 数组)?一个用于包含 hello 的前两行,另一个用于包含 world 的下两行.我基本上需要为第一列中唯一的东西获取一个单独的嵌套列表(所以你好"和世界"以前不知道).

Is there a way in python that I can somehow parse the list that I obtain from reading this data to obtain two separate nested lists (or a numpy array)? One for the first two rows containing hello and the other for the next two rows containing world. I basically need to get a separate nested list for something unique in the first column (so "hello" and "world" are not previously known).

推荐答案

使用 dict 并按第一列分组:

Use a dict and group by the first column:

from csv import  reader
from collections import defaultdict
with open("in.txt") as f:
    d = defaultdict(list)
    for k, v in reader(f,delimiter=" "):
        d[k].append(v)

print(d.values())

这将为您提供两个单独列表中的所有值:

Which will give you all the values in two separate lists:

[['25', '26'], ['12', '56']

如果数据总是在两个部分,您可以使用 groupby:

If the data is always in two sections you can use a groupby:

from itertools import groupby
from csv import  reader
from operator import itemgetter

with open("in.txt") as f:
    print([list(map(itemgetter(1), v)) 
           for k, v in groupby(reader(f,delimiter=" "), key=itemgetter(0))])

哪个将给出相同的输出:

Which will give the same output:

 [['12', '56'], ['25', '26']]

这篇关于根据唯一值将列表拆分为两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆