附加另一个变量除了在列表理解中迭代的内容(python)

时间:2015-05-13 02:57:47

标签: python

我在下面有这个循环,它工作正常,但我想尝试将其转换为列表理解

   medname = []
   for med in medicationsTextBoxLocatorTextBox:
        if med.get_attribute("value") != "":
            a = med.get_attribute("value")
            medname.append(a)

我试过这个:

medname = [med for med in medicationsTextBoxLocatorTextBox if med.get_attribute("value") != ""]

现在填充列表很好但我发现的是我不知道如何做这部分a = med.get_attribute("value")我不知道如何将其纳入列表理解

我试过了:

medname = [a = med.get_attribute("value") for med in medicationsTextBoxLocatorTextBox if med.get_attribute("value") != ""]
确定它失败了。

我们如何将a = med.get_attribute("value")放入列表理解中?

我对python很新,并且避开了列表推导,但决定今天第一次尝试。

那我们该怎么做呢?

2 个答案:

答案 0 :(得分:0)

There is no reason to set a equal to anything because it will just be replaced the next time around. Try this:

medname = [med.get_attribute('value') for med in medicationsTextBoxLocatorTextBox if med.get_attribute('value') != ""]

If you really want to set a variable, then you'll just have to use a regular for loop because list comprehension is only meant for creating lists, not carrying out commands.

答案 1 :(得分:0)

The problem with your above is you're not getting the attribute. Correct would be:

 medname = [med.get_attribute("value") for med in medicationsTextBoxLocatorTextBox if med.get_attribute("value") != ""]

Of course, this technically has redundant efforts, which can be problematic if med.get_attribute is expensive or stateful. In that case, you can use a generator expression:

values = (med.get_attribute("value") for med in  medicationsTextBoxLocatorTextBox)
medname = [value for value in values if value != ""]

Now the expression uses no intermediary data structures, and only calls get_attribute once per iteration.