0

So I have a few lists, as follows:

group1 = ["AS", "AT", "AW"]
group2 = ["Bob", "Steve"]
group3 = ....

I want a create a new list as below (basically creating a tuple or paired data, that pairs each data point with its variable name):

combined = [["AS", "group1"], ["AT", "group1"], ["AW", "group1"], ["Bob", "group2"], ["Steve", "group2"]....]

I found some code that lets me do this for one list, namely

one_list_at_time = []
for item in Group1:
    temp = item, [i for i, a in locals().items() if a == group1][0]
    one_list_at_time.append(temp)

but I can't figure out the code/syntax to allow me to do this over multiple lists at once (as I don't know how to point python to the underlying variable name), i.e.

all_groups = group1 + group2 + .... + groupn

all_data = []

for item in all_groups:

    #problem is with below line
    temp = item, [i for i, a in locals().items() if a == item][0]

    all_data.append(temp)

The output of all_data (using only group1 and group2) should be as set forth in 'combined' above.

As I'm a Noob, simple answers I can follow/implement are appreciated over clever ones that I can't. Thanks,

Mike
  • 201
  • 2
  • 14
  • 4
    Code logic relaying on variable names makes no sense and should not be attempted. Use a dictionary instead. – CristiFati Jul 30 '22 at 09:06

1 Answers1

0

You can store lists and their names as dictionary. And then combine them.I think, getting variable names is impossible so you should store them as string.

group1 = ["AS", "AT", "AW"]
group2 = ["Bob", "Steve"]
all_lists = {"group1": group1, "group2": group2}

combined= []
for key, value in all_lists.items():
    for item in value:
        combined.append([item, key])
print(combined)