I am looking for some guidance on how to work with nested lists and unpacking them. Previously, I had created 4 separate lists to store the responses from users in a survey with one lists storing gender, another a Y/N question, the age and BMI of the survey user.
I want to try and use only a single list by nesting each instance of a survey response as a nested list. I then need to be able to print the nested list contents out and eventually write to a csv file. I already understand the file i/o requirements, my challenge is more about iterating over nested lists to produce outputs like below.
As this is for a course I am doing there are some limitations in that I can only use list data types to store the data, I cannot use for loops and sys.stdout.write is to be used instead of print.
Sample list
records = [["M", "N", 37, 34.67], ["F", "Y", 22, 29.01], ["F", "Y", 88, 24.00]]
Output Requirement 1
["M", "N", 37, 34.67]
["F", "Y", 22, 29.01]
["F", "Y", 88, 24.00]
Output Requirement 2 (CSV)
M,N,37,34.67
F,Y,22,29.01
F,Y,88,24.00
CodePudding user response:
Here is a solution with while loops.
import sys
i = 0
sample = [["M", "N", 37, 34.67], ["F", "Y", 22, 29.01], ["F", "Y", 88, 24.00]]
while i < len(sample):
sys.stdout.write(str(sample[i]) "\n") # 1st form needed
j = 0
while j < len(sample[i]):
sample[i][j] = str(sample[i][j])
j = 1
sys.stdout.write(",".join(sample[i]) "\n") # 2nd form needed
i = 1