derkyzer
derkyzer

Reputation: 161

Condensing Repetitive Code in Python?

Ways to condense these?

col1 = [row1[0],row2[0],row3[0],row4[0],row5[0]]
col2 = [row1[1],row2[1],row3[1],row4[1],row5[1]]
col3 = [row1[2],row2[2],row3[2],row4[2],row5[2]]
col4 = [row1[3],row2[3],row3[3],row4[3],row5[3]]
col5 = [row1[4],row2[4],row3[4],row4[4],row5[4]]

printedxrow1 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row1.count(0))+"  TOTAL: "+str(sum(row1))]
printedxrow2 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row2.count(0))+"  TOTAL: "+str(sum(row2))]
printedxrow3 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row3.count(0))+"  TOTAL: "+str(sum(row3))]
printedxrow4 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row4.count(0))+"  TOTAL: "+str(sum(row4))]
printedxrow5 = ["[X]","[X]","[X]","[X]","[X]","  <- V: "+str(row5.count(0))+"  TOTAL: "+str(sum(row5))]

I'm mainly just unsure of how to stop the repetition with changing variables. Thanks.

Upvotes: 1

Views: 196

Answers (2)

Jo So
Jo So

Reputation: 26531

rows = [row1,row2,row3,row4,row5]  # you'd generate rows in a cleaner way    

cols = list(zip(*rows))

printedxrows = [ ("[X]","[X]","[X]","[X]","[X]","  <- V: {}   TOTAL: {}"
                                               .format(row.count(0), sum(row)))
                 for row in rows ]

Note I've also made it a format string for better readability.

Upvotes: 1

falsetru
falsetru

Reputation: 369424

col1 = [row1[0],row2[0],row3[0],row4[0],row5[0]]
col2 = [row1[1],row2[1],row3[1],row4[1],row5[1]]
col3 = [row1[2],row2[2],row3[2],row4[2],row5[2]]
col4 = [row1[3],row2[3],row3[3],row4[3],row5[3]]
col5 = [row1[4],row2[4],row3[4],row4[4],row5[4]]

Above lines can be replaced with:

col1, col2, col3, col4, col5 = zip(row1, row2, row3, row4, row5)

>>> zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
<zip object at 0x0000000002B17FC8>
>>> col1, col2, col3 = zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
>>> col1
(1, 4, 7)
>>> col2
(2, 5, 8)
>>> col3
(3, 6, 9)

See zip.

Upvotes: 4

Related Questions