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?

3
  • 2
    Use variables of that name, or use a dictionary, or a NamedTuple? Thousand options... Commented Jul 25, 2016 at 10:19
  • 2
    a, b, c, d = sims1, but please read 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. Commented Jul 25, 2016 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. Commented Jul 25, 2016 at 10:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for that. But is there a way to do it in array type, instead of creating a dictionary?
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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.