473,748 Members | 10,058 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Finding attributes in a list

Ben
Hi

In a list I have a number of soccer players. Each player has a
different rating for attacking, defending, midfield fitness and
goalkeeping.

I have devised a while loop that goes through this list to find the
best player at defending, attacking, midfield and goalkeeping. However
there is more than one defender per team so I therefore need it to find
the next best player.

Below is the code used to ascertain the best defender:
# STUFF TO FIND THE TOP DEFENDER
defender = 0 # The position of defender is set to the first player
in the knowledge base
topdefender = 0
c = 3 # the defensive rating of the first player in the list
d = (len(squadList)-4) # the defensive rating of the last player in the
list.

while c <= d:
if squadList[c] > topdefender:
topdefender = squadList[c]
defender = squadList[c-3] + " " + squadList[c-2] # The
defender variable is assigned to the forename and surname of the player
c = c + 8 # Move to the defensive rating of the next player in the
list

print defender

any help on this would be greatly appreciated.

thank you

Jul 18 '05 #1
7 1491
You can use the new 'sorted' built-in function and custom "compare"
functions to return lists of players sorted according to any criteria:
players = [ .... {'name' : 'joe', 'defense' : 8, 'attacking' : 5, 'midfield' : 6,
'goalkeeping' : 9},
.... {'name' : 'bob', 'defense' : 5, 'attacking' : 9, 'midfield' : 6,
'goalkeeping' : 3},
.... {'name' : 'sam', 'defense' : 6, 'attacking' : 7, 'midfield' : 10,
'goalkeeping' : 4}
.... ] def cmp_attacking(f irst, second): .... return cmp(second['attacking'], first['attacking'])
.... [p['name'] for p in sorted(players, cmp_attacking)] ['bob', 'sam', 'joe']


Jul 18 '05 #2
infidel wrote:
You can use the new 'sorted' built-in function and custom "compare"
functions to return lists of players sorted according to any criteria:

players = [
... {'name' : 'joe', 'defense' : 8, 'attacking' : 5, 'midfield' : 6,
'goalkeeping' : 9},
... {'name' : 'bob', 'defense' : 5, 'attacking' : 9, 'midfield' : 6,
'goalkeeping' : 3},
... {'name' : 'sam', 'defense' : 6, 'attacking' : 7, 'midfield' : 10,
'goalkeeping' : 4}
... ]
def cmp_attacking(f irst, second):
... return cmp(second['attacking'], first['attacking'])
...
[p['name'] for p in sorted(players, cmp_attacking)]


['bob', 'sam', 'joe']


Or more efficiently, use the key= and reverse= parameters:

py> players = [
.... dict(name='joe' , defense=8, attacking=5, midfield=6),
.... dict(name='bob' , defense=5, attacking=9, midfield=6),
.... dict(name='sam' , defense=6, attacking=7, midfield=10)]
py> import operator
py> [p['name'] for p in sorted(players,
.... key=operator.it emgetter('attac king'),
.... reverse=True)]
['bob', 'sam', 'joe']

STeVe
Jul 18 '05 #3
On Tue, 29 Mar 2005 11:29:33 -0700, Steven Bethard <st************ @gmail.com> wrote:
infidel wrote:
You can use the new 'sorted' built-in function and custom "compare"
functions to return lists of players sorted according to any criteria:

>players = [


... {'name' : 'joe', 'defense' : 8, 'attacking' : 5, 'midfield' : 6,
'goalkeeping' : 9},
... {'name' : 'bob', 'defense' : 5, 'attacking' : 9, 'midfield' : 6,
'goalkeeping' : 3},
... {'name' : 'sam', 'defense' : 6, 'attacking' : 7, 'midfield' : 10,
'goalkeeping' : 4}
... ]
>def cmp_attacking(f irst, second):


... return cmp(second['attacking'], first['attacking'])
...
>[p['name'] for p in sorted(players, cmp_attacking)]


['bob', 'sam', 'joe']


Or more efficiently, use the key= and reverse= parameters:

py> players = [
... dict(name='joe' , defense=8, attacking=5, midfield=6),
... dict(name='bob' , defense=5, attacking=9, midfield=6),
... dict(name='sam' , defense=6, attacking=7, midfield=10)]
py> import operator
py> [p['name'] for p in sorted(players,
... key=operator.it emgetter('attac king'),
... reverse=True)]
['bob', 'sam', 'joe']

Perhaps the OP doesn't yet realize that Python also provides the ability
to define custom classes to represent players etc. E.g., using instance attribute
dicts instead of raw dicts (to save typing ;-):
class Player(object): ... def __init__(self, **kw): self.__dict__.u pdate(kw)
... def __repr__(self): return '<Player %s>'%getattr(se lf, 'name', '(anonymous)')
... players = [ ... Player(name='jo e', defense=8, attacking=5, midfield=6),
... Player(name='bo b', defense=5, attacking=9, midfield=6),
... Player(name='sa m', defense=6, attacking=7, midfield=10)] players [<Player joe>, <Player bob>, <Player sam>] import operator
[p.name for p in sorted(players, key=operator.at trgetter('attac king'), reverse=True)]

['bob', 'sam', 'joe']

And then he could create a Team class which might have players as an internal list,
and provide methods for modifying the team etc., and generating various reports
or calculating and/or retrieving data. Not to mention properties for dynamically
caclulated attributes etc ;-)

Regards,
Bengt Richter
Jul 18 '05 #4
> class Player(object):
def __init__(self, **kw): self.__dict__.u pdate(kw)
def __repr__(self): return '<Player %s>'%getattr(se lf, 'name', '(anonymous)')

import operator
[p.name for p in sorted(players, key=operator.at trgetter('attac king'), reverse=True)]


Just happened to read this thread and wanted to say this is a neat
little example-- thank you! I have a couple of followup questions.

(1) Is there a performance penalty for using key=operator.at trgetter()?
(2) The Player class looks like a nice model for a data table when one
wants to sort by arbitrary column. Would you agree?
(3) Suppose one wished to construct a player list from a collection of
attribute lists, e.g.,

names = ['bob', 'sam', 'linda']
attack = [7, 5, 8]
defense = [6, 8, 6]
# construct players list here

Can you recommend an efficient way to construct the player list?

Thanks!
Marcus
Jul 18 '05 #5
On Saturday 02 April 2005 08:44 pm, Marcus Goldfish wrote:
(2) The Player class looks like a nice model for a data table when one
wants to sort by arbitrary column. Would you agree?
The Player class is (and any class) is absolutely fabulous when you have
heterogenous data (string, int, etc). I would not fall into the trap of LoDs
(Lists of Dictionaries). They get unwieldy because you always have to manage
them with functions. You end up writing a module built around your specific
dictionary and you end up with a duct-taped object oriented design anyway.
Classes are way better--so use them up front, even if you think that your
data structure will never be complicated enough to warrant a class. It
eventually will if it is worth a damn to begin with. Given this is a soccer
team we are talking about, it is definitely worth being a full fledged class.
However, if it were basketball...
(3) Suppose one wished to construct a player list...[snip]


team = [Player(azip[0],azip[1],azip[2]) for azip in zip(names,attac k,defense)]
You have to love listcomp.

Better (IMHO) would be

team = [Player(azip) for azip in zip(names,attac k,defense)]

where a Player might come to life with

class Player(object):
def __init__(self, atup):
self.name, self.attack, self.defense = atup

BUT, even way better (again, IMHO) would be

ateam = Team(zip(names, attack,defense) )

where team could be initialized by a tuple:

class Team(list):
def __init__(self, azip):
for azip in alist:
self.data.appen d(Player(atup))

James

--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 18 '05 #6
On Saturday 02 April 2005 09:51 pm, James Stroud wrote:
where team could be initialized by a tuple:

* class Team(list):
* * def __init__(self, azip):
* * * for azip in alist:
* * * * self.data.appen d(Player(atup))


Sorry, this should read:

where team could be initialized by a list of tuples:

class Team(list):
def __init__(self, azip):
for atup in azip:
self.data.appen d(Player(atup))

--
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Jul 18 '05 #7
On Sat, 2 Apr 2005 23:44:11 -0500, Marcus Goldfish <ma********@gma il.com> wrote:
class Player(object):
def __init__(self, **kw): self.__dict__.u pdate(kw)
def __repr__(self): return '<Player %s>'%getattr(se lf, 'name', '(anonymous)')

import operator
[p.name for p in sorted(players, key=operator.at trgetter('attac king'), reverse=True)]
Just happened to read this thread and wanted to say this is a neat
little example-- thank you! I have a couple of followup questions.

(1) Is there a performance penalty for using key=operator.at trgetter()?

I would think sorted would make it as efficient as possible, but possibly.
I can conceive of low level optimization for key=<some C builtin that can be recognized>
But timing is best ;-) Also, vs what? There are a number of alternatives.
(2) The Player class looks like a nice model for a data table when one
wants to sort by arbitrary column. Would you agree? Depends on scale, and what else use you have for a custom object representation. E.g.,
(using below lists available from interactive session below) a plain dict by names (unique required)
with (attack, defense) tuples as values is probably pretty efficient and fast.
dict(zip(names, zip(attack, defense))) {'linda': (8, 6), 'bob': (7, 6), 'sam': (5, 8)}

But if objects are going to be complex and have methods or properties, OO makes it easy.
(3) Suppose one wished to construct a player list from a collection of
attribute lists, e.g.,

names = ['bob', 'sam', 'linda']
attack = [7, 5, 8]
defense = [6, 8, 6]
# construct players list here

Can you recommend an efficient way to construct the player list?

I wouldn't worry about efficiency unless you are dealing with a database of
all the worlds teams ;-) (And in that case, you probably want to look into
interfacing with the database your data is already in, to let it do things
for you natively e.g. via SQL).

If you know the "columns" as matching attribute lists as above, zip will associate them
into tuples. Also, I used a keyword argument in the Player __init__ above because I
wanted to copy and paste the dict calls from the prior post, but knowing exact columns,
I'd probably do some thing like:
class Player(object): ... def __init__(self, name, attack=None, defense=None): # require name
... self.name = name
... self.attack = attack
... self.defense = defense
... names = ['bob', 'sam', 'linda']
attack = [7, 5, 8]
defense = [6, 8, 6]

Then the players list is just players = [Player(*tup) for tup in zip(names, attack, defense)] where *tup unpacks a tuple from the output of zip into the arg list of Player's __init__.

And you can extract the names like [player.name for player in players] ['bob', 'sam', 'linda']

Or whatever you want for player in players: print player.name, player.attack, player.defense ...
bob 7 6
sam 5 8
linda 8 6

As mentioned, zip makes tuples of corresponding elements of its argument lists: zip(names, attack, defense) [('bob', 7, 6), ('sam', 5, 8), ('linda', 8, 6)]

If you had huge input lists, you could avoid the terporary tuple list using import itertools
iplayers = list(itertools. starmap(Player, itertools.izip( names, attack, defense)))
for player in iplayers: print player.name, player.attack, player.defense

...
bob 7 6
sam 5 8
linda 8 6

You can look into __slots__ if you want to have objects but need reduced memory footprint.
But don't worry about optimizing 'til you can prove you need it, unless just for fun ;-)

Ok. That's enough relief for me. Got other stuff ...

Regards,
Bengt Richter
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2688
by: Francis Avila | last post by:
A little annoyed one day that I couldn't use the statefulness of generators as "resumable functions", I came across Hettinger's PEP 288 (http://www.python.org/peps/pep-0288.html, still listed as open, even though it's at least a year old and Guido doesn't seem very hot on the idea). I'm not too sure of its ideas on raising exceptions in generators from outside (although it looks like it might be convenient in some cases), but being able...
2
3000
by: Steve | last post by:
Hi, I have a very long string, someting like: DISPLAY=localhost:0.0,FORT_BUFFERED=true, F_ERROPT1=271\,271\,2\,1\,2\,2\,2\,2,G03BASIS=/opt/g03b05/g03/basis, GAMESS=/opt/gamess,GAUSS_ARCHDIR=/opt/g03b05/g03/arch, GAUSS_EXEDIR=/opt/g03b05/g03/bsd:/opt/g03b05/g03/private:/opt/g03b05/g
3
1614
by: Gadrin77 | last post by:
<Restaurants> <FastFood> <DriveIn Name="Del Taco"/> <DriveIn Name="McDonalds"/> <DriveIn Name="Bakers"/> <DriveIn Name="Arbys"/> <DriveIn Name="Green Burrito"/> <DriveIn Name="Jack in the Box"/> <DriveIn Name="Green Burrito"/> <DriveIn Name="KFC"/>
6
1354
by: Russell Warren | last post by:
Is there any better way to get a list of the public callables of self other than this? myCallables = classDir = dir(self) for s in classDir: attr = self.__getattribute__(s) if callable(attr) and (not s.startswith("_")): myCallables.append(s) #collect the names (not funcs)
6
1214
by: Matthew Wilson | last post by:
I sometimes inadvertently create a new attribute on an object rather update a value bound to an existing attribute. For example: In : class some_class(object): ...: def __init__(self, a=None): ...: self.a = a ...: In : c = some_class(a=1)
19
420
by: Kirk Strauser | last post by:
Given a class: how can I find its name, such as: 'foo' I'm writing a trace() decorator for the sake of practice, and am trying to print the name of the class that a traced method belongs to. This seems like it should be easy, but I think I've been staring at the problem too
5
1321
by: Nathan Harmston | last post by:
Hi, Sorry if the subject line of post is wrong, but I think that is what this is called. I want to create objects with class Coconuts(object): def __init__(self, a, b, *args, **kwargs): self.a = a self.b = b
10
2477
by: Bobby Roberts | last post by:
hi group. I'm new to python and need some help and hope you can answer this question. I have a situation in my code where i need to create a file on the server and write to it. That's not a problem if i hard code the path. However, the domain name needs to be dynamic so it is picked up automatically. The path to our websites is home/sites/xxxxx/ where xxxxx represents the domain name.
275
12345
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
8823
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9312
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9238
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8237
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4593
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.