-1

Lets say I have some variables that evaluate to either true or false:

firstValue = true
secondValue = false
thirdValue = true

And I put them in a list:

def list = [firstValue, secondValue, thirdValue]

I want to iterate through the list and check if each value returns true or false, if the value is true I want to be able to print the name i.e. firstValue

for (item in list){
    if (item == true){
        println("${item} is true")
    }
}

This is just printing "true is true"

sirius78m
  • 3
  • 1
  • 1
    Maybe just use a dict? – Meh Jun 14 '23 at 15:52
  • You might find this useful [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – JonSG Jun 14 '23 at 15:58
  • you didn't put *variables* into a list. Lists, and other container types, contain **objects**. not *variables*. Variables are not objects. Objects don't retain any information about the names of any variables that might be referencing them. If *you want to associate a string object with some other object, then you have to write code that does that*. A typical approach might be to use a dictionary, or to use a tuple – juanpa.arrivillaga Jun 14 '23 at 16:15
  • why is this tagged with Python *and* Groovy? – juanpa.arrivillaga Jun 14 '23 at 16:17

2 Answers2

0

Your list only holds the values (true/false), so it's 'hard' to get the key back.

Consider using a dictionary, which holds some keys that you can iterate to show both the key and value

data = {
    "firstValue": True,
    "secondValue": False,
    "thirdValue": True
}

for key, value in data.items():
    if value:
        print(key, "is true")
firstValue is true
thirdValue is true
Try it online!

If you really need a separate list of keys, you can use the following instead of calling items()

listOfKeys = list(data.keys())

for key in listOfKeys:
    if data[key]:
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Exactly what I needed. Think I'll try figure out adding these to a dictionary instead and printing the keys this way. Thanks so much! – sirius78m Jun 14 '23 at 16:27
0

Not sure, why the other answer was accepted even though it's written all the way in Python (???), but in Groovy you have 2 options:

  1. in a Script you can grab the variables by their names like so:
firstValue = true
secondValue = false
thirdValue = true

def list = this.binding.variables.grep{ 'out' != it.key }

for (item in list){
    if (item.value){
        println "$item.key is true"
    }
}
  1. You declare your data in a Map (how the dict is officually called in java) and iterate over those:
def map = [ firstValue:true, secondValue:false, thirdValue:true ]

for (item in map){
    if (item.value){
        println "$item.key is true"
    }
}

In both cases you'll get the following printed:

firstValue is true
thirdValue is true
injecteer
  • 20,038
  • 4
  • 45
  • 89