0

I would like to know how I add the values for a few arrays which start with "yoyo" in one matrix.

The code:

yoyo_asd=('a','b','c')
yoyo_bsd=('asd','111','222')
matrix=[]

I am trying with something like this but nothing..

for vars in dir():
  if vars.startswith("yoyo"):
    matrix.append([vars])

This is my goal:

matrix = [
    ['a','b','c'],
    ['asd','111','222'],
]
sshashank124
  • 31,495
  • 9
  • 67
  • 76
yoyo
  • 21
  • 4

4 Answers4

4

Should be a one-liner:

matrix = [list(val) for key, val in globals().items() if key.startswith('yoyo')]
Sam Chats
  • 2,271
  • 1
  • 12
  • 34
2

You could just use the vars which returns a dict of the local namespace like:

>>> yoyo_asd=('a','b','c')
>>> yoyo_bsd=('asd','111','222')
>>> matrix=[]
>>> for key, val in vars().items(): # if you are want a global namespace, then use `globals()`
...   if key.startswith('yoyo'):
...     matrix.append(val)
... 
>>> matrix
[('a', 'b', 'c'), ('asd', '111', '222')]
>>> 

Help on built-in function vars in module builtins:

vars(...) vars([object]) -> dictionary

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
han solo
  • 6,390
  • 1
  • 15
  • 19
0

Try like this what u want i would work like that.


yoyo_asd=('a','b','c')
yoyo_bsd=('asd','111','222')
matrix=[]
for vars in dir():
  if vars.startswith("yoyo"):
    matrix.append([i for i in vars])
0

convert tuple to list and iterate over to append to matrix.

matrix.append(list(yoyo_asd))
matrix.append(list(yoyo_bsd))    


>>> yoyo_asd=('a','b','c')
>>> yoyo_bsd=('asd','111','222')

>>> matrix=[]
>>> matrix.append(list(yoyo_asd))
>>> matrix.append(list(yoyo_bsd))
>>> matrix
 [['a', 'b', 'c'], ['asd', '111', '222']]
>>> 
Nidhi Rai
  • 36
  • 7