[英]Python right to left diagonal list
I would like a list to be stored into another list from right to left diagonally without importing anything if possible 我希望将一个列表从右到左对角地存储到另一个列表中,如果可能的话不导入任何内容
eg. list =
[[1, 4, 6]
[6, 3, 7]
[2, 7, 9]]
say I'd like to store [6, 3, 2] into another list, how would i go about doing it? 说我想将[6,3,2]存储到另一个列表中,我该怎么做呢? I have tried many ways for hours and still cant find a solution
我已经尝试了许多小时的方法,但仍然找不到解决方案
The following snipped 以下内容已被删除
l =[[1, 4, 6],
[6, 3, 7],
[2, 7, 9]]
d = len(l)
a = []
for i in range(0,d):
a.append(l[i][d-1-i])
print(a)
results in the output you expected: 产生您期望的输出:
[6, 3, 2]
When you want to create a list out from another list, list comprehension is a very good way to go. 当您想从另一个列表创建一个列表时,列表理解是一个很好的方法。
a = yourlist
print([a[i][(i+1)*-1] for i in range(len(a))])
This list comprehension loops through the lists taking the the furthes back integer and the second furthes back and so on. 此列表理解会循环遍历列表,并返回第二个整数,依此类推。
With a list comprehension: 具有列表理解:
l =[[1, 4, 6],
[6, 3, 7],
[2, 7, 9]]
diagonal = [row[-i] for i, row in enumerate(l, start=1)]
print(diagonal)
[6, 3, 2]
You can use a list comprehension and use list indexing twice to select your row and column: 您可以使用列表推导并使用列表索引两次来选择行和列:
L = [[1, 4, 6],
[6, 3, 7],
[2, 7, 9]]
n = len(L)
res = [L[i][n-i-1] for i in range(n)]
# [6, 3, 2]
An alternative formulation is to use enumerate
as per @OlivierMelançon's solution. 另一种替代方法是按照@OlivierMelançon的解决方案使用
enumerate
。
If you can use a 3rd party library, you can use NumPy to extract the diagonal of a flipped array: 如果可以使用第三方库,则可以使用NumPy提取翻转数组的对角线:
import numpy as np
arr = np.array(L)
res = np.diag(np.fliplr(arr))
# array([6, 3, 2])
Using numpy and rotate (90) 使用numpy并旋转(90)
import numpy as np
list = [[1, 4, 6],[6, 3, 7],[2, 7, 9]]
np.diag(np.rot90(array))
Output : 输出:
array([6, 3, 2])
or without using numpy: 或不使用numpy:
list = [[1, 4, 6],[6, 3, 7],[2, 7, 9]]
res=[]
i=-1
for elm in list :
res.append(elm[i])
i-=1
print res
#[6, 3, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.