0

I'm trying to find a solution to quickly test and thus switch a very long list of variables. I've named them as such:

mcp1pin1
mcp1pin2
mcp1pin3
...
mcp2pin1
mcp2pin2
mcp2pin3
...

As such, typing them all out manually would be quite difficult and long, and so I thought I could use the count() function to do this for me.

I've tried:

while True:
        count = 0
        while count < 16:
           mcp1pin(count).value = True
           time.sleep(0.1)
           mcp1pin(count).value = False
           count = count +1

But I could not make this work.... I feel like I might be close. Anyone has any suggestion for me? Thank you!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Kagetaze
  • 13
  • 3
  • What is the output of this? And what is it that you want, exactly? It seems that `eval` could do the trick. – MatBBastos Jun 30 '21 at 21:16
  • Is there something preventing you from using a list for this? You could for example have `mcp[0][0]=mcp1pin1`, `mcp[0][1]=mcp1pin2`, `mcp[1][0]=mcp2pin1` and so on for all of them. Iterating over a list will be a lot quicker/cleaner than trying to manipulate similarly named variables. – Tyberius Jun 30 '21 at 22:02
  • What `count()` function are you referring to? [`itertools.count()`](https://docs.python.org/3/library/itertools.html#itertools.count)? Or maybe you mean `range`? – wjandrea Jul 01 '21 at 02:05

1 Answers1

0

Don't use a very long list of variables in the first place, use a data structure like a list instead.

You haven't mentioned what the actual values are, but here's some pseudocode:

mcps = [
    [<mcp1pin1>, <mcp1pin2>, <mcp1pin3>, ...],
    [<mcp2pin1>, <mcp2pin2>, <mcp2pin3>, ...],
    ...
    ]

For a more concrete example, you could do something like this:

class Pin:
    def __init__(self, value=False):
        self.value = False

mcps = [
    [Pin() for _ in range(3)]
    for _ in range(2)
    ]

for mcp in mcps:
    for pin in mcp:
        pin.value = True

Although, lists start at 0 and you lose the "pin" from the name, so you could consider using dicts like this, though it's more clunky IMO:

mcps = {
    i: {'pins': {
        j: Pin() for j in range(1, 4)
        }}
    for i in range(1, 3)
    }

for mcp in mcps.values():
    for pin in mcp['pins'].values():
        pin.value = True

Note: dicts preserve insertion order as of Python 3.7.


Related: How do I create variable variables?

wjandrea
  • 28,235
  • 9
  • 60
  • 81