I have four lists
apps = ["App 1", "App 2", "App 3", "App 4"]
devices = ["device1"]
groups = ["group1", "group2", "group3", "group4"]
rules_name = ["rule1", "rule2", "rule3", "rule4", "rule5"]
and I need to iterate over each list adding the index of each list to it's correct index in the new list, something like this...
The None
would indicate that there are no other items in the list, in this case the device
list
rows = [
[apps[0], devices[0], groups[0], group_rules[0]],
[apps[1], None ,groups[1], group_rules[1]],
[apps[2], None ,groups[2], group_rules[2]],
[apps[3], None ,groups[3], group_rules[3]],
[apps[4], None ,groups[4], group_rules[4]],
# The rows list can have any number of rows based on the size of the lists above.
]
I've tried looping over each list which just created a pyramid of loops and did not give the correct results. I also tried list comprehension but I'm not super well versed in those so maybe I did it wrong.
For what it's worth, I'm using the Rich library which requires either a list of rows or adding a bunch of
table.add_row("App1", "Device1", "group1", "rule1")
However, I'm not sure how to make that dynamic as the original four lists will vary in size each time I run this code.
This could be solved by obtaining the size of the longest list and iterating over that amount times, each time checking whether the size of each list is lesser than the current index. if it is larger you simply append the current item in that index of the list, otherwise put None.
apps = ["App 1", "App 2", "App 3", "App 4"]
devices = ["device1"]
groups = ["group1", "group2", "group3", "group4"]
rules_name = ["rule1", "rule2", "rule3", "rule4", "rule5"]
#get length of all lists
apps_len = len(apps)
devices_len = len(devices)
groups_len = len(groups)
rules_name_len = len(rules_name)
#determine number of rows based on the longest list
max_size = max(apps_len, devices_len, groups_len, rules_name_len)
rows = []
for i in range(max_size):
current_row = []
if i < apps_len:
current_row.append(apps[i])
else:
current_row.append(None)
if i < devices_len:
current_row.append(devices[i])
else:
current_row.append(None)
if i < groups_len:
current_row.append(groups[i])
else:
current_row.append(None)
if i < rules_name_len:
current_row.append(rules_name[i])
else:
current_row.append(None)
rows.append(current_row)