根据元组列表中的第二个值找到元组后,返回元组的第一个元素

时间:2020-10-08 04:41:26

标签: python list

我有一个元组列表,看起来像这样:

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]

我想根据第二个值找到所述元组后返回元组的第一项。我可以做类似的事情:

for pair in list_of_tuples:
    if pair[1] == something:
        print(pair[0])

# or

[pair[0] for pair in e1_span_sent_pairs if pair[1] == something][0]

但是我想知道是否有一种方法可以不使用for循环来做到这一点。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以创建一个字典,以便ot可以重用,如下所示:

var gestures = require("tns-core-modules/ui/gestures");
var labelModule = require("tns-core-modules/ui/label");
var label = new labelModule.Label();
label.on(gestures.GestureTypes.tap, function (args) {
    console.log("Tap");
});

输出:

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]

d = {v: (k, v) for k, v in list_of_tuples}

print(d['a'])
print(d['c'])

如果(1, 'a') (3, 'c') 循环使您烦恼,则会导致相同的for

dict

答案 1 :(得分:1)

如果您确实不希望循环(即使不是简单的列表理解形式),也可以执行以下操作:

 fetch("    http://192.xx.x.xxx/abc-bin/output?username=one&password=xxxx&action=on&pin=relay")
  .then(function (response) {
    return response.json();
  })

但是我只是去理解列表并拆开元组的两个元素:

result = map(lambda i: i[0], filter(lambda i: i[1] == 'c', list_of_tuples))