3

I have the following list of lists:

sims1 = [[(2, 0.90452874), (1, 0.83522302), (4, 0.77591574), (0, 0.72705799), (3, 0.52282226)],
         [(3, 0.79298556), (1, 0.78112978), (2, 0.76006395), (0, 0.58570701), (4, 0.40093967)],
         [(2, 0.9549554),  (1, 0.71705657), (0, 0.58731651), (3, 0.43987277), (4, 0.38266104)],
         [(2, 0.96805269), (4, 0.68034023), (1, 0.66391909), (0, 0.64251828), (3, 0.50730866)],
         [(2, 0.84748113), (4, 0.8338449),  (1, 0.61795002), (0, 0.60271078), (3, 0.20899911)]]

I would like to name each list in the list according to these strings: url = ['a', 'b', 'c', 'd']. So for example,

>>> a
[(2, 0.90452874), (1, 0.83522302), (4, 0.77591574), (0, 0.72705799), (3, 0.52282226)]
>>> b 
[(3, 0.79298556), (1, 0.78112978), (2, 0.76006395), (0, 0.58570701), (4, 0.40093967)]

etc. So how do I accomplish this in Python?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Technologic27
  • 341
  • 3
  • 4
  • 13
  • 2
    Use variables of that name, or use a dictionary, or a NamedTuple? Thousand options... – Marcus Müller Jul 25 '16 at 10:19
  • 2
    `a, b, c, d = sims1`, but please read [What is the XY-problem?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Please describe the problem you want to solve, not the problem you encountered halfway on your way to a solution. – dhke Jul 25 '16 at 10:20
  • 1
    The way you're asking this, it remains unclear. What do you mean with "label"? you should really add an example of how you'd like to use tthis. – Marcus Müller Jul 25 '16 at 10:20

2 Answers2

7

You can use dictionary:

names = ['a', 'b', 'c', 'd', 'e']
named_sims1 = dict(zip(names, sims1))
print(named_sims1['a'])

If you want to access the variables as a instead of x.a or x['a'], you can use this:

exec(",".join(names) + ' = ' + str(sims1)) # ensure same length

But I am not sure, if this is recommended.

DurgaDatta
  • 3,952
  • 4
  • 27
  • 34
  • thank you for that. But is there a way to do it in array type, instead of creating a dictionary? – Technologic27 Jul 26 '16 at 01:08
  • If we can convert the given list to its string form, we can use exec with multiple assignment. However, I am not sure how we can serialize an arbitrarily listed list to string (I have asked it in SO now). In your case, the nesting is predefined, so we can convert it into string in a cumbersome way, but I dont think that is worth it. – DurgaDatta Jul 26 '16 at 02:53
3

Use zip() and dict():

result = dict(zip(url, sims1))

Make sure that the elements in url are strings like 'a' rather than a variable name like a, or the definition of url will fail with a NameError.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97