1

I have a list of tuples in 'tups' and have applied the following code to filter. The list of tuples have the format [(floata,stra1,stra2),(floatb,strb1,strb2),...etc]

keys=sorted({t[2] for t in tups}) 
for key in keys:     
    group=filter(lambda t: t[2]==key,tups)     
    print '{}:\n\tmax: {}\n\tmin: {}'.format(key,max(group),min(group))

Initially I thought the curly brackets was a mistake and changed them to square brackets. I did not get a syntax error but the code did not work. As a last resort I changed the brackets back and everything was fine. Can someone explain the construction. Is this a dictionary comprehension? Where is this explained in the documentation?

4

2 回答 2

4

If you mean the curly brackets in the first line, this is a set comprehension. This will create a set of the third item from every tuple in tups. A set is similar to a list, but without order, and therefore cannot contain duplicates.

If you mean the brackets in the string, this is just new-style string formatting. Calling str.format() changes those braces into the passed values.

于 2012-09-26T14:33:55.127 回答
0

Before Python 2.6, you would have used:

print '%s:\n\tmax: %s\n\tmin: %s' % (key,max(group),min(group))

to format a string using placeholders (the %s).

Since Python 2.6, you can use the {} syntax for the placeholder and .format instead:

print '{}:\n\tmax: {}\n\tmin: {}'.format(key,max(group),min(group))

or using positional arguments:

print '{0}:\n\tmax: {2}\n\tmin: {1}'.format(key,min(group),max(group))

(notice that I changed the order of the arguments, but the output is the same: we used {2} to represent the third argument...)

Just an advice: when you get a lot of arguments, it's easier to name them, as:

print '{key}:\n\tmax: {groupmax}\n\tmin: {groupmin}'.format(key=key,groupmin=min(group),groupmax=max(group))

The .format syntax is more powerful than the % one: examples are available in the documentation.

于 2012-09-26T14:38:26.227 回答