Reputation: 214
I have a complicated list arrangement. There are many lists, and some of them have sub-lists. Now, some of the elements from the aforementioned lists are to be printed. What makes it more complicated is, the index of the value to be printed is in an excel file, as shown here:
[list_1,1,2] #Means - list[1][2] is to be printed (sub-lists are there)
[list_2,7] #Means - list_2[7] is to be printed (no sub-list)
................
[list_100,3,6] #Means list_100[3][6] is to be printed (sub list is there)
The number of the lists is so long, so that I was using a for loop and multiple if statements. For example (pseudo code):
for i in range(100): #because 100 lists are there in excel
if len(row_i) == 3:
print(list_name[excel_column_1_value][excel_column_2_value])
else:
print(list_name[excel_column_1_value])
Please note that, the excel sheet is only to get the list name and index, the lists are all saved in the main code.
Is there any way to avoid the if statements
and automate that part as well ? Asking because, the if condition value is only based on the length given by the excel sheet. Thanks in advance.
Upvotes: 0
Views: 49
Reputation: 77399
Suppose you have data like this:
data = {
"list1": [[100, 101, 102], [110, 111, 112], [120, 121, 123]],
"list2": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
"list3": [[200, 201, 202], [210, 211, 212], [220, 221, 223]],
}
If it is homework, your teacher probably want you to solve it using recursion, but I recommend using an iterative version in Python unless you can assure you would not stack more than 999 calls:
fetch_element(data, listname, *indices):
value = data[listname]
for index in indices:
value = value[index]
return value
Then you have the list of elements you want:
desired = [
["list1", 0, 0],
["list2", 7],
["list3", 2, 2],
]
Now you can do:
>>> [fetch_element(data, *line) for line in desired]
[100, 7, 223]
Which is the same as:
>>> [data["list1"][0][0], data["list2"][7], data["list3"][2][2]]
[100, 7, 223]
Upvotes: 1
Reputation: 2400
Can you post a better example? how does your list look like and what's the desired output when printing?
You can open the file, read the indexes and lists names you want to print into a list and iterate that list to print what you want.
There are many ways to print a list a simple one, you can use:
mylist = ['hello', 'world', ':)']
print ', '.join(mylist)
mylist2 = [['hello', 'world'], ['Good', 'morning']]
for l in mylist2:
print(*l)
Upvotes: 1