简体   繁体   English

如何在 2 元组集中找到具有特定第一个元素的 2 元组?

[英]How can I find 2-tuples with a specific first element in the set of 2-tuples?

I have a set of pairs with types (str, int).我有一组类型对(str,int)。 I shall find the tuples that contain specific string and then increment the corresponding integer by 1. I know how to find tuples in a set with asking whether myTuple in mySet .我将找到包含特定字符串的元组,然后将相应的整数加 1。我知道如何通过询问myTuple in mySet是否有myTuple in mySet来查找集合中的元组。 But I do not know the way to handle such situations.但我不知道如何处理这种情况。 I will appreciate any help.我将不胜感激任何帮助。

Here is an example set :这是一个示例集:

from sets import Set
up = 2
down = 3
right = 1
left = 2
mySet = Set([("up",up),("down",down),("right",right),("left",left)])

Say from mySet I want to increment the second of the pair where its first element is "up" by 1 so I need something likemySet说我想将第一个元素"up"的对的第二个增加 1 所以我需要类似的东西

if ("up",ref) in mySet:
    ref += 1 

By doing this, I want to increment both the value of the original variable up and second element of the tuple.通过这样做,我想增加原始变量的两个值up的元组和第二个元素。

I would suggest using a dictionary for your purpose.我建议您使用字典来达到您的目的。 That way, the re-assignment of the new count would be more clean and easier to interpret.这样,新计数的重新分配将更清晰且更易于解释。 For instance:例如:

>>> my_set = { 'up': 0, 'down': 0, 'left': 0, 'right': 0 }
>>> my_set['up'] += 1
>>> my_set
{'up': 1, 'down': 0, 'left': 0, 'right': 0}

As Brian describes, tuples are non-mutable so each time you update the count it has to be created a new one with the updated count.正如 Brian 所描述的,元组是不可变的,因此每次更新计数时,都必须使用更新后的计数创建一个新的元组。 This can then be used to replace the old tuple.这可以用来替换旧的元组。

you can use the filter method to find all entries in the set where your condition, in this case the first entry being "up" is true.您可以使用 filter 方法查找符合您条件的集合中的所有条目,在这种情况下,第一个条目为“up”为真。

subset = list(filter(lambda x: x[0] == "up", mySet))
for entry in subset:
    mySet.remove(entry)
    newEntry = (entry[0],(entry[1]+1))
    mySet.add(newEntry)
    up +=1 

you cannot use entry+=1 because tuples are non-mutable in python你不能使用entry+=1因为元组在 python 中是不可变的

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

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