[英]Python, slicing lists?
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
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. zip(*field)
将行转置为列, reversed()
然后反转结果。 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; 围绕
zip()
调用的list()
调用使我们可以反转Python 3中的迭代器结果; it can be dropped in Python 2. 可以在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
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.