Re: [Tutor] Variable Question

2016-11-20 Thread Bryon Adams

On 11/18/2016 08:16 PM, Alan Gauld via Tutor wrote:

for index, item in enumerate(prefix):
prefix[index] = item[1]




I forgot about enumerate! That helped me clean up and actually finish my 
next exercise as I was having trouble working for my lists the way I was 
previously.


Thank you very much =)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Variable Question

2016-11-20 Thread Peter Otten
Bryon Adams wrote:

> On 11/18/2016 08:16 PM, Alan Gauld via Tutor wrote:
>> for index, item in enumerate(prefix):
>> prefix[index] = item[1]
>>
>>
> 
> I forgot about enumerate! That helped me clean up and actually finish my
> next exercise as I was having trouble working for my lists the way I was
> previously.
> 
> Thank you very much =)

enumerate() is a useful tool, but given the code you provide in your 
original post I recommend that you build a new list rather than modifying 
the existing one:

prefix = []
for item in entries:
prefix.append(item[1])

The above is such a common pattern that Python offers syntactic sugar called 
"list comprehension" to write this:

prefix = [item[1] for item in entries]

In both cases the original entries list is not changed.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Generic dictionary

2016-11-20 Thread Thorsten Kampe
[Crossposted to tutor and general mailing list]

Hi,

I'd like to extend the dictionary class by creating a class that acts 
like a dictionary if the class is instantiated with a dictionary and 
acts like a "dictitem" ([(key1, value1), (key2, value2), ...]) if 
instantiated with a list (that is dictitem).

The code (see extract at bottom) works well but it contains a lot of 
"if this is a dictionary then do as a dictionary already does" 
boilerplate code". How can I "inherit"(?)/"subclass"(?)/derive from 
dict so I don't have to write the code for the dictionary case?

Thorsten

```
class GenericDict:
"""
a GenericDict is a dictionary or a list of tuples (when the keys
are not hashable)
"""
def __init__(inst, generic_dict):
inst._generic = generic_dict

def __getitem__(inst, key):
if isinstance(inst._generic, dict):
return inst._generic[key]
else:
return inst.values()[inst.keys().index(key)]

def values(inst):
if isinstance(inst._generic, dict):
return inst._generic.values()
else:
try:
return list(zip(*inst._generic))[1]
except IndexError:  # empty GenericDict
return ()

def keys(inst):
if isinstance(inst._generic, dict):
return inst._generic.keys()
else:
try:
return list(zip(*inst._generic))[0]
except IndexError:  # empty GenericDict
return ()
```

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor