简体   繁体   中英

Get index of a shallow tuple/list given an item in said tuple

What's a graceful way in Python to get an index of a shallow tuple given an itme in it?

Example

For words and spelling variants/aliases, get the word given any variant/alias:

words = (('word1')
         ('word2', 'variant2_1')
         ('word3', 'variant3_1', 'variant3_2')
         ...
         )

word = get_some_word()
if index_of_tuple_containing_word != None:
    word = words[index][0]

Notes:

  1. variants are unique across words.

  2. We don't want to unpack the structure into (word, variant) tuples.

  3. The above can also apply to words or variants as keys in a dict, but I thought this structure is simpler.

For this example, I'd make a dict from word variants to their canonical forms:

words = {'word1': 'word1',
         'word2': 'word2', 'variant2_1': 'word2',
         'word3': 'word3', 'variant3_1': 'word3', 'variant3_2': 'word3',
         ...
}
word = words[word]

Lookup is constant-time, unlike the tuple of tuples, where lookup would require a brute-force search through about half the data structure. If you want all variants of a word, the value can be a list of variants.

If for some reason you really want to organize your data as a tuple of tuples, and you really want to compute an index into the outer tuple, you can write a function to do that easily enough:

def outer_index(item, nested_tuple):
    for i, inner_tuple in enumerate(nested_tuple):
        if item in inner_tuple:
            return i
    raise ValueError('{} is not in the nested tuple'.format(item))

It'll be slow, but if your data set isn't that big, it may be okay.

OP:

I also liked:

words = ( ('word1',('word1', 'alias11', 'alias111')),
          ('word2',('word2', 'alias22', 'alias222')),
          ('word3',('word3',)) )

someword = 'alias11'
lst = [cword for cword,aliases in words if someword in aliases]   
canonical = lst[0] if lst else None

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