简体   繁体   中英

How can a non-integer value be used as the index of a (2D) list?

If we would like to address a location in a 2D list in python with non-integer values, for example with a string in the form of a tuple, how can the indexing be handled? I am using dictionary as a solution, but I am not sure if it is the best solution.

Exampe:

mylist = {'a1':{"('p1','p2')":10, "('p1','p3')":11}, 'a2':{"('p4','p5')":12, "('p4','p6')":13}}

and now:

mylist['a1']["('p1','p2')"] = 20

I think it is not an efficient solution. Any other solution please?

What I understand is that you're trying to make the second dimension tuple-shaped. So, what if you just turn the strings into tuples?

For example:

>>> mylist = {'a1': {('p1','p2'): 10, ('p1','p3'): 11}, 'a2': {('p4','p5'): 12, ('p4','p6'): 13}}
>>> mylist['a1'][('p1','p2')]
10

I cannot comment on your posts at this time because my reputation score is not enough. Oops. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM