简体   繁体   中英

Populating a 2D list with two different variables

I'm trying to created a 2D list, with 2 positions in each list but with two different variables.

This is for a school project, the name is meant to come first and then a homework mark which I would like to insert later. This is my code so far:

student_group_list = ['BERRY-SMITH Finlay', 'EDWARDS Elizabeth', 'GREGORY Isabella', 'Hendley-Jones Annabel', 'LIS Natalia', 'MANNING Sophie', 'RATCLIFFE George', 'BELLAMY Jacob', 'BOUGHTON Grace', 'GARNETT Archie', 'Maruta Kudzai', 'DAVELIS Alexander', 'DENMAN David', 'JENKIN Jonathan', 'LISTER Thomas', 'CLOWES Edward', 'OGG Holly', 'PUGH Billy']

hwklist = [[student_group_list[i] for j in range(2)] for i in range(len(student_group_list))]
print (hwklist)

I'm want it to output

[['BERRY-SMITH Finlay', ''], ['EDWARDS Elizabeth', '']...

but right now I'm getting

[['BERRY-SMITH Finlay', 'BERRY-SMITH Finlay'], ['EDWARDS Elizabeth', 'EDWARDS Elizabeth']...

I want to know if there is any way that I can insert variable 1 into the index 0, and variable 2 into the index 1 when the 2D list is created. Thank you for any help.

You can do it in the same way you declare the student_group_list , manually:

result = [[student, ''] for student in student_group_list]
print(result)

Output

[['BERRY-SMITH Finlay', ''], ['EDWARDS Elizabeth', ''], ['GREGORY Isabella', ''], ['Hendley-Jones Annabel', ''], ['LIS Natalia', ''], ['MANNING Sophie', ''], ['RATCLIFFE George', ''], ['BELLAMY Jacob', ''], ['BOUGHTON Grace', ''], ['GARNETT Archie', ''], ['Maruta Kudzai', ''], ['DAVELIS Alexander', ''], ['DENMAN David', ''], ['JENKIN Jonathan', ''], ['LISTER Thomas', ''], ['CLOWES Edward', ''], ['OGG Holly', ''], ['PUGH Billy', '']]

But if the names of the students are unique, I suggest you use a dictionary instead of a nested list. With the names as keys and the marks as values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM