简体   繁体   中英

For element in list of tuples, return other element in tuple

Below is my code for a function that searches a list of tuples called pairs. Each tuple in the list is comprised of two elements.

The element given in the function (called item) could be in the 0 or 1 position of the tuple, but all the tuples in the list are composed of only 2 elements.

pairs = [('a','b'),('c','d'),('e','f'),('c','a')]

def connections(pairs, item):
    output = ''
    for j in pairs:
        if item in j:
            output = output + str(j)
    return (output)

Right now this code will pull out the entire tuple(s) that have the item within them.

I'd like to change this code to only return the other element in the tuple and to return it as a string instead of a tuple.

This should do what you want:

def connection(pairs, item):
    return ''.join([p[1-p.index(item)] for p in pairs if item in p])

Here's some sample output:

>>> connection([('a','b'),('c','d'),('e','f'),('c','a')], 'a')
'bc'

Instead of checking for membership, check for equality.

def connections(pairs, item):
    output = ''
    for j in pairs:
        if item == j[0]:
            output += j[1]
        elif item == j[1]:
            output += j[0]
    return output

Note that I've streamlined the concatenation into augmented assignment and removed the unnecessary str() calls, as they are already strings. Or you could do it as follows:

def connections(pairs, item):
    return ''.join(j[0] if item==j[1] else j[1] if item==j[0] else '' for j in pairs)
pairs = [('a','b'),('c','d'),('e','f'),('c','a')]

def connections(pairs, item):
    output = ''
    for j in pairs:
        if item in j:
            index = 1-j.index(item)
            output = output + str(j[index])
    return (output)

print(connections(pairs, 'c'))

Output:

da

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