简体   繁体   中英

Shortening Repetitive Code in Python 3.x?

I think I'm starting to get the hang of this. For this code:

printedxrow7 = ["V "+str(cols[0].count(0)),"V "+str(cols[1].count(0)),"V "+str(cols[2].count(0)),"V "+str(cols[3].count(0)),"V "+str(cols[4].count(0))]
printedxrow8 = [str(sum(cols[0])),str(sum(cols[1])),str(sum(cols[2])),str(sum(cols[3])),str(sum(cols[4]))]
numgood = (((rows[0]).count(2))+((rows[0]).count(3)+(rows[1]).count(2))+((rows[1]).count(3))+((rows[2]).count(2))+((rows[2]).count(3))+((rows[3]).count(2))+((rows[3]).count(3))+((rows[4]).count(2))+((rows[4]).count(3)))

I'm thinking to condense this to:

rows = [[convert[random.randint(0,7)] for _ in range(5)] for _ in range(5)]
cols = list(zip(*rows))
printedrows = ["\n"+ "[X]"*5 + "  <- V: {}   TOTAL: {}".format(row.count(0), sum(row)) for row in rows]
printcolvolt = ["V:{}".format(col.count(0) for col in cols)]
printcolcount = ["T:{}".format(sum(col) for col in cols)]
numgood = numtiles - rows.count(0)

Why do I get the at 0x030116C0> error? (I added the rest of the code for context.)

Well you have a SyntaxError (missing closing parenthesis on the format call) in lines 1 and 2, and have put it in the wrong place when editing your post.

printcolvolt = ["V:{}".format(col.count(0)) for col in cols]
                                          ^

Otherwise, you format the generator col.count(0) for col in cols itself, rather than the values it generates.

For line 3, I think you should have something like

numgood = sum(row.count(2) + row.count(3) for row in rows)

otherwise, you are trying to count how many zeroes there are in what I assume is a list of lists, which will always give zero. I don't know what numtiles is.

NB It would be more helpful if you said what the problem actually was (eg input, expected output, actual output/error) rather than just "why wouldn't this work".

You have to add the parentheses right after the function you are referring to:

printcolvolt = ["V:{}".format(col.count(0)) for col in cols]
printcolcount = ["T:{}".format(sum(col)) for col in cols]

Otherwise,

#WRONG
printcolvolt = ["V:{}".format(col.count(0) for col in cols)]

will create a generator object (which you see with generator object <genexpr> at ... ) and try to print this, because the for ... in is inside the parentheses.

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