简体   繁体   中英

List of lists chunked into sublists

I have a list of lists I'm using as a data container. I've left all of my debugging code in, everything goes to console so I can follow it through, which explains some of the more redundant print statements.

It's created by iterating through and making one long list that looks like:

[['Arsenal', 2.47, 1.2, 0.89, 'Chelsea', 2.15, 0.8, 1.21,...

The sublists are all of uniform length (9 elements), so I used the following to chunk it, which is taken from here :

# This function should chunk the 'file', as when we run the above code, 
# we'll end up with one incredibly long list that contains every team on the same line
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))

for group in chunker(league_stats, 9):
   print repr(group)
   final_stats.append(repr(group))
   print "printing final stats"
   print final_stats
   print "and here's a line break" 

It then should look like this:

[['Arsenal', 2.47, 1.2, 0.89], ['Chelsea', 2.15, 0.8, 1.21]...]

But if I print it it's showing as:

["['Arsenal', 2.47, 1.2, 0.89]", ['Chelsea', 2.15, 0.8, 1.21|]..."]

If i iterate through it, it seems to show as expected

So that seems to have made each entire sublist a string, rather than a list, is that right? This has two weird knock ons - if I access elements using final_stats[0][2], for example, it gives me an 'A' instead of 'Arsenal', which I would expect.

The other, of course, is that I can't run logical operations against list elements - what's the best way to chunk the long list, or to stop this from happening?

If you need the full code (not included here for brevity), then it's here - I suspect that this question was inadvertantly caused by the issue in this post.

Someone on that answer suggested using dictionaries as a better data container - I'm pretty happy with the list structure, and it feels (to me as a newbie) a bit simpler for what I want to do - these data structures are always uniform sizes, so I don't want to change the data types unless I really have to. I think it's a helpful thing I'll look into long term.

repr() gets the representation of a string. ie:

print repr("""Hello!
this is a test string
yay.""")

Returns:

'Hello!\nthis is a test string\nyay.'

In your code, it is converting a list to a string, and that is why when you do [0][2] you get a character and not something you would expect.

There's no need to call it in your code. Just append the chuncked list normally.

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