能够访问容器Python中的项目的同时编写循环的最佳方法

时间:2018-06-21 15:17:34

标签: python loops

这是一个相对直接但相对尖锐的问题,关于如何编写最简明的if / any / for循环来实现我所需的功能。我对Python相当陌生,并且更习惯于C ++的处理方式。

我需要执行以下操作:

map(paste0("X", 1:1000), ~
                    df %>%
                        filter(!! (rlang::sym(.x)) ==0) %>%
                        select(group) %>%
                        distinct
              )  

我已经将其浓缩为这样的东西:

for item in my_dict:
    if some_var == item.some_attribute:
        if item.another_attribute exists:
            variable = "A"
        else variable = "B"
        print "Duplicate item exists in my list of type: {}".format(variable)

但是,这样做时,我收到if any(some_var == item.some_attribute for item in my_dict): variable = "A" if item.another_attribute else "B" print "Duplicate item exists in my list of type: {}".format(variable) 的“未解决的引用”错误。关于如何编写简洁的循环,等价检查和状态检查的任何想法,就像我上面所描述的那样,可以让我在item上访问和执行方法?

谢谢!

编辑:非常感谢您提供@pjhaugh的答案,这正是我想要的。作品精美!谢谢大家的宝贵意见。

3 个答案:

答案 0 :(得分:0)

这里发生的是item不会泄漏到生成器表达式范围之外(这是一件好事)。您可以通过获取生成器产生的下一个东西或捕获该生成器不产生任何东西来获取item

try:
    item = next(item for item in my_dict if some_var == item.some_attribute)
    variable = "A" if item.another_attribute else "B"
except StopIteration:
    # there is no such item in my_dict

答案 1 :(得分:0)

正如我在评论中所指出的-any(some_var == item.some_attribute for item in my_dict)建立了自己的本地范围。您不能在其外部使用item

不过,您可以像这样遍历字典:

创建minimal verifyable complete example数据:

class K:
    def __init__(self):
        self.some_attribute = None
        self.another_attribute = None

    def __repr__(self):
        return "{}  - {}".format(self.some_attribute,self.another_attribute)
    def __str__(self):
        return "{}  - {}".format(self.some_attribute,self.another_attribute)

k1 = K()
k1.some_attribute = 99
k2 = K()
k2.some_attribute = 33
k3 = K()
k3.some_attribute = 33
k3.another_attribute = 1

my_dict = { 1: k1, 2:k2, 3:k3}
some_var = 33

您可以像这样使用for循环:

variable = None
for item in my_dict.items():
    k,v = item
    if v.some_attribute != some_var:
        print "No dupe: {}".format(v)
        continue
    if v.some_attribute == some_var and v.another_attribute is not None:
        variable = "A"
    else: 
        variable = "B"
    print "Duplicate item exists in my list of type: {}".format(variable)
    print v

输出:

No dupe: 99  - None
Duplicate item exists in my list of type: B
33  - None
Duplicate item exists in my list of type: A
33  - 1

答案 2 :(得分:0)

您可以像这样在for循环中提取迭代器产生的对象

   for item in (i for i in my_dict if some_var == item.some_attribute):
        variable = "A" if item.another_attribute is not None else "B"
        print("Duplicate item exists in my list of type: {}".format(variable))
        break
   else:  # no break encountered
       ...  # not found

当前,您正在遍历字典的键。如果需要这些项(在c ++术语中为对),则需要my_dict.items()