简体   繁体   English

对于元组列表中的元素,返回元组中的其他元素

[英]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. 函数中给定的元素(称为item)可以位于元组的0或1位置,但是列表中的所有元组仅由2个元素组成。

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. 请注意,我已经将串联简化为扩充分配,并删除了不必要的str()调用,因为它们已经是字符串了。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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