splitting a list into two lists based on a unique value

2024/11/20 11:35:22

I have a text file that looks something like this:

hello 12
hello 56
world 25
world 26

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).

Answer

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']

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

from itertools import groupby
from csv import  reader
from operator import itemgetterwith 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']]
https://en.xdnf.cn/q/119833.html

Related Q&A

Customize axes in Matplotlib

I am a beginner with Python, Pandas and Matplotlib. I would like to customize the entries at the axes of a scatter plot. I have the following data:So on the x-axis there should be 5 entries, with the f…

how to show the max and min from user input?

Nevermindif xmin == 1:print(ymin)I tried using the max and min but I get a typeerror which is int object not iterable.

To output a string without whitespce

My program:def string_splosion(str):j=1c=len(str)i=0s=while(i<c):s=s+(str[:i+j])i=i+1print sprint("Enter a string:") s=raw_input() string_splosion(s)Sample input:Code Expected output:CCoCo…

Regex replace `a.b` to `a. b`? [duplicate]

This question already has answers here:Python: Replace with regex(2 answers)Closed 6 years ago.I am trying to change all strings of the type a.b to a. b. It should also work if any of the characters ar…

Is there something wrong with this line of Python code?

I tried this line of code, and it kept giving me the SyntaxError.print(/ / - / \ / | * 30, end=\r)^It pointed on the brackets. Any suggestions? Thanks!

TypeError: tuple indices must be integers or slices, not str postgres/python

Hi Im trying to get a timestamp from a row called time in my postgres database, however Im getting the error. Its the second row in the database. The error TypeError: tuple indices must be integers or …

Pandas Python: KeyError Date

I am import into python where it will automatically create a date time object.However I want the first column to be a datetime object in Python. Data looks likeDate,cost 41330.66667,100 41331.66667,101…

How to resample 1 minute data into 15 minute data?

CSV file. df before resample and after applying: df["dateandtime"] = (pd.to_datetime(df.pop("DATE").str.cat(df.pop("TIME"), sep=" "))) df = df.set_index(pd.Datet…

Python Pygame Lighting for Pong

Hey Guys Im writing a little Pong-Game in Pygame and wanted to use a glowing-effect on the Ball and the Bats. But Pygame dosent support this effects and make solid blocks out of it. Is there a way to h…

python - List.remove method not applicable as the function with the map builtin?

Question Can List.remove not be used as the function to apply in the map(function, iterable, ...) builtin? %%timeit import random m = _max = 10000 n = random.randint(1, m)outer = random.sample(populat…