0

So I have a list of list called templist like this:

[['C0', 1, 1], ['NA', 4, 5], ['NA', 3, 7], ['C3', 9, 3], ['NA', 8, 4], ['NA', 7, 5], ['C6', 6, 6], ['NA', 5, 10]]

The way you create a namedtuple for the above list is:

from collections import namedtuple

Vertex = namedtuple('Vertex', ['NAME', 'x', 'y'])

vertices = [
    Vertex('C0', 1, 1), 
    Vertex('NA', 4, 5), 
    Vertex('NA', 3, 7), 
    Vertex('C3', 9, 3), 
    Vertex('NA', 8, 4), 
    Vertex('NA', 7, 5), 
    Vertex('C6', 6, 6), 
    Vertex('NA', 5, 10)
           ]

The above namedtuple must look like this on printing

print vertices

[Vertex(NAME='C0', x=1, y=1), Vertex(NAME='NA', x=4, y=5), Vertex(NAME='NA', x=3, y=7), Vertex(NAME='C3', x=9, y=3), Vertex(NAME='NA', x=8, y=4), Vertex(NAME='NA', x=7, y=5), Vertex(NAME='C6', x=6, y=6), Vertex(NAME='NA', x=5, y=10)]

I need it to be this way since I had added another distance field to this and converted it to a dictionary with nested key value pairs. So I absolutely MUST have it this way. (Trying to implement K-MEANS)

Other answers related to this, like the one in this, Creating a namedtuple from a list can't apply to this, since this is a list of lists. EDIT: IT DOES APPLY, YOU HAVE TO JUST MODIFY IT AS SUGGESTED IN THE COMMENTS

My question is, how do I DYNAMICALLY create a named tuple in the above format of vertices from any given list of lists in the format of templist

In other words, all I want to do is supply a list of lists in format of templist (since that list is generated by another function so it will change every-time you run the program) and generate DYNAMICALLY a named tuple in the above format of vertices

  • 5
    How does that not apply? `[Vertex(*x) for x in templist]` is an application of the accepted answer in that question, and applies here – inspectorG4dget Aug 23 '17 at 21:05
  • I'm sorry, I'm a beginner and I didn't know adding the `for x in templist part` will solve the problem. I'll try it out and let you know. –  Aug 23 '17 at 21:07
  • IT WORKED.. I'm sorry this became nothing but a duplicate.. –  Aug 23 '17 at 21:09
  • `[Vertex(a,b,c) for a,b,c in templist]` but the purpose as above, `*x` will explode the tuple into its components. – Fallenreaper Aug 23 '17 at 21:09
  • Even more efficient is using `_make` so you use the `list`s directly. `[Vertex._make(x) for x in templist]`, or with `map`, `map(Vertex._make, templist)`. – ShadowRanger Aug 23 '17 at 21:12

0 Answers0