Python: Check if list of named tuples contains particular attribute value

2024/10/4 7:28:43

I have a list of named tuples:

from collections import namedtupleT = namedtuple('T', ['attr1', 'attr2', 'attr3', 'attr4'])
t1 = T('T1', 1, '1234', 'XYZ')
t2 = T('T2', 2, '1254', 'ABC')
t3 = T('T2', 2, '1264', 'DEF')
l = [t1, t2, t3]

I want to check if an element exists in the list T where attr1 = 'T2'.

Checking if the list contains such an element by doing:

any(x for x in l if x.attr1 == 'T2')

only returns the information whether such a namedtuple is in the list or not.
I would like to also pop this namedtuple from the list.
One way of doing it is:

if any(x for x in l if x.attr1 == 'T2'):result = [x for x in l if x.attr1 == 'T2'].pop()

However, I don't like this solution, since I'm looping over the list l twice.

Is there any better/more-elegant way of doing this?

Answer

How about an old-school for loop? Simple, elegant, and you loop only once.

for x in l:if x.attr1 == 'T2':breakresult = x
https://en.xdnf.cn/q/70634.html

Related Q&A

javascript error: arguments[0].scrollIntoView is not a function using selenium on python

Im using Selenium on python and I would like to scroll to an element to click on it. Everywhere I see that the rigth things to do to go directly to the element is to use :driver = webdriver.Chrome() dr…

Uploading a static project to google app engines

Disclaimer: I already asked here, but apparently off-topic. I want to set up a page using this bootstrap template and host it as a static website using the google appengine service. Inside the google_a…

Python cannot import DataFrame

I am trying to use Pandas in Python to import and manipulate some csv file.my code is like:import pandas as pd from pandas import dataframe data_df = pd.read_csv(highfrequency2.csv) print(data_df.col…

Sum of product of combinations in a list

What is the Pythonic way of summing the product of all combinations in a given list, such as:[1, 2, 3, 4] --> (1 * 2) + (1 * 3) + (1 * 4) + (2 * 3) + (2 * 4) + (3 * 4) = 35(For this example I have t…

discord.py: How to get the user who invited/added the bot to his server? [solution]

I want to send a DM to the user, who invited/added the bot to his server. I noticed that its displayed in the audit log. Can I fetch that and get the user or is there a easier way to achieve that? Ex…

How to reorder the keys of a dictionary?

I have multiple dictionaries inside the list. I want to sort the dictionary with the custom key. In my case, I want to sort it using Date key. By that, I mean to move the Date key to the first position…

How do bitwise operations work in Python?

I have been learning about Bitwise operations today and I learned that Not (~) inverses all bits, e.g.:01010 to 10101which means ~10 should be -5 but instead I have seen that it is -11 (per the python …

How to split large wikipedia dump .xml.bz2 files in Python?

I am trying to build a offline wiktionary using the wikimedia dump files (.xml.bz2) using Python. I started with this article as the guide. It involves a number of languages, I wanted to combine all th…

CherryPy interferes with Twisted shutting down on Windows

Ive got an application that runs Twisted by starting the reactor with reactor.run() in my main thread after starting some other threads, including the CherryPy web server. Heres a program that shuts d…

From subprocess.Popen to multiprocessing

I got a function that invokes a process using subprocess.Popen in the following way:def func():...process = subprocess.Popen(substr, shell=True, stdout=subprocess.PIPE)timeout = {"value": Fal…