[Tutor] nested list help
Nick Raptis
airscorp at otenet.gr
Tue Jul 27 16:41:52 CEST 2010
On 07/27/2010 04:48 PM, Evert Rol wrote:
>
> On the other hand, if you want to combine lists based on their first element, consider using dictionaries and extend lists which have the same key. Depending on how you create the lists (eg, when reading columns from a file), you can actually do this during creationi.
>
I'm very much with Everet on this one. Your data would be better
contained in a dictionary as such:
x = {'NM100': [3, 4, 5, 6, 7, 10, 11, 12, 13],
'NM200': [15, 16, 17]}
Choosing your data structure is, most of the time, as important as the
rest of your code.
The rest of the time, the format of your input is not something you can
control so:
If your data is already on a nested list, as it's on your example, you
can convert them quite easily to a dictionary.
You then can manipulate them with ease, and if you do want them back on
nested list format, convert them back.
Here's a very quick script I wrote on how to do it.
Please read it through and hit me with questions on what you don't
understand.
-------------------------------------------------------------
input = [['NM100', 3, 4, 5, 6, 7],
['NM100', 10, 11, 12, 13],
['NM200', 15, 16, 17]]
# Convert and combine the input into a dictionary
output_dict = {}
for entry in input:
key = entry[0]
values = entry[1:]
if key in output_dict:
output_dict[key].extend(values)
else:
output_dict[key] = values
print output_dict
# Convert the dictionary back into a nested list
output = []
for key in output_dict:
entry = output_dict[key]
entry.insert(0, key)
output.append(entry)
print output
----------------------------------------------------------------
Of course, my script is very basic and it doesn't tend to a lot of
things you'd might want, like eliminating double values or sorting, but
it should start you on your path.
Nick
More information about the Tutor
mailing list