Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python namedtuple slice

this is my first question here...

if I have a namedtuple like the below

 FDResult = namedtuple('FDResult', ['S', 'Payoff', 'V'])

and I have an array that has a collection of namedtuple like the below

 bla = [FDResult(S=100.0, Payoff=0.0, V=0.4693541525097441),
 FDResult(S=102.0, Payoff=1.0, V=0.4944046100897207),
 FDResult(S=104.0, Payoff=1.0, V=0.5188897967596792),
 FDResult(S=106.0, Payoff=1.0, V=0.5427339609362274),
 FDResult(S=108.0, Payoff=1.0, V=0.5658731041633024)]

How do I get an array slice of S?

 bla[:].S #I want to get [100.0,102.0,104.0,...] as a result

that doesn't work with error: AttributeError: 'list' object has no attribute 'S'...

Any suggestion appreciated. Thanks.

like image 224
pacifictoy Avatar asked Sep 04 '26 22:09

pacifictoy


1 Answers

I think you want a list comprehension, for example

[x.S for x in bla[:]]

You can of course substitute a more general slice of your list in there, e.g. bla[1:-1:2].

like image 57
wim Avatar answered Sep 07 '26 12:09

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!