2

i really need your help with slicing a list.

lets say I've got a list of lists like this:

field=[[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]

and I have to write a function which will return a string that will look like this:

42334
44423
21142
14221

thus fat i managed to do this:

def out(field):
    b=''
    for list in field:
        list1=list[::-1]
        b+=''.join((str(sth) for sth in list1))+'\n'
    return b

which returns this:

4421
2414
3412
3242
4321
Rok Dolinar
  • 976
  • 3
  • 13
  • 29

2 Answers2

3

You need to transpose your list of rows to a list of columns, as well as reverse the results of the transposition to get a proper rotation.

zip(*field) transposes the rows to columns, reversed() then reverses the results. Combined with a list comprehension you can do this all in one expression:

def out(field):
    return '\n'.join([''.join(map(str, c)) for c in reversed(list(zip(*field)))])

or spelled out into an explicit loop:

def out(field):
    b = []
    for columns in reversed(list(zip(*field))):
        b.append(''.join(map(str, columns)))
    return '\n'.join(b)

The list() call around the zip() call allows us to reverse the iterator result in Python 3; it can be dropped in Python 2.

Demo:

>>> field=[[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
>>> [''.join(map(str, c)) for c in reversed(list(zip(*field)))]
['42334', '44423', '21142', '14221']
>>> '\n'.join([''.join(map(str, c)) for c in reversed(list(zip(*field)))])
'42334\n44423\n21142\n14221'
>>> print('\n'.join([''.join(map(str, c)) for c in reversed(list(zip(*field)))]))
42334
44423
21142
14221
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0
def out(field):
    b=''
    a=[]
    while len(field[0])>0:
        for list in field:
            a.append(list.pop())
        a.append("\n")
    a="".join(str(x) for x in a)
    return a 
x=[[1, 2, 4, 4], [4, 1, 4, 2], [2, 1, 4, 3], [2, 4, 2, 3], [1, 2, 3, 4]]
print out(x)
Anurag Goel
  • 468
  • 10
  • 15