I'm working with a LIST that am getting from a soup which after the clean up gives me:
lists of variable length ['7.0', '7.5', '6.8', '6.9'] or ['7.0', '7.5']

so my problem is when I try formating the output:

code snippet:

if grades:
    print '\r\n["' + str(student[0]),
    if len(grades) == 1:
        print ('%s'*len(grades)) % tuple(grades)

the output of this is:

["John Doe 7.0 7.5 6.8 6.9

however what I need is:
["John Doe, ["7.0","7.5"],["6.8","6.9"]] or ["John Doe, ["7.0","7.5"]]

I've tried with Formatter and Template and seems can't be done with those.

thank you

Recommended Answers

All 5 Replies

Why you want unbalanced " and what is the logic? Why such stupid format, sorry to ask?

just because I need it like that :(

You will use something similar to the following (but this code is not complete), tutorial for for loop at Click Here explaination of list append and extend at Click Here

grades = ['7.0', '7.5', '6.8', '6.9']
for ctr in range(0, len(grades), 2):
    print grades[ctr], grades[ctr+1]

Tony's question was probably referring to

if len(grades) == 1:
    print ('%s'*len(grades)) % tuple(grades)

I would suggest that you test this further, i.e. if len(grades) == 1 then why multiply the output by len(grades) which is just one.

It appears

  • that you have an even number count in your lists of grades ...


  • you want the output to be formatted as a list of list pairs ... but with the name as the fist element in the outer list.

So ...

# nameGradePairsList.py #

grades = [ '4.5', '4.4', '3.9', '4.2', '3.8', '3.7' ]

grade_pair_lst = [ 'Sue Girl' ]
pair = []
for i, grd in enumerate(grades):
    if i % 2 == 0:
        pair.append( grd )
        pair.append( grd )
        grade_pair_lst.append( pair )
        pair = []

print( grade_pair_lst )
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.