我想简化的数组怪异问题。
我有一系列列表,例如:
list1 = 'abc'
list2 = 'def'
...
listN = 'xyz'
我需要像这样将它们压缩在一起:
[['a', 0, 0, ..., 0],
['b', 0, 0, ..., 0],
['c', 0, 0, ..., 0],
[0, 'd', 0, ..., 0],
[0, 'e', 0, ..., 0],
[0, 'f', 0, ..., 0],
[...],
[0, 0, 0, ..., 'x'],
[0, 0, 0, ..., 'y'],
[0, 0, 0, ..., 'z']]
我还有一个限制,那就是numpy
不是一个选择。
是否有一种简单的方法可以使用itertools
? (它不必是列表,因为以后会像for r in row: for c in column:
现在我正在这样做:
array1 = [[0 for i in range(n)] for j in range(m)]
step_i = 0
for i, a in enumerate([listA, listB, ..., listN]):
for b in a:
array1[step_i][I] = b
step_i += 1
但这太丑了!
答案 0 :(得分:0)
我认为使它看起来“不那么丑陋”的唯一方法是用生成器替换临时数组并摆脱step_i
。
这是我设法做到的:
def diag_zip(*lists):
for i, a in enumerate(lists):
for el in a:
row = [0 for _x in range(len(lists))]
row[i] = el
yield row
if __name__ == '__main__':
print(list(diag_zip('abc', 'def', 'ghi', 'xyz')))
它输出(由我格式化)
[['a', 0, 0, 0], ['b', 0, 0, 0], ['c', 0, 0, 0],
[0, 'd', 0, 0], [0, 'e', 0, 0], [0, 'f', 0, 0],
[0, 0, 'g', 0], [0, 0, 'h', 0], [0, 0, 'i', 0],
[0, 0, 0, 'x'], [0, 0, 0, 'y'], [0, 0, 0, 'z']]
答案 1 :(得分:0)
from pprint import pprint
import string
# Generates the ['abc', 'def', ..., ] list.
abc = string.ascii_lowercase
three = lambda l, i: f"{l[i-1]}{l[i]}{l[i+1]}"
lists = [three(abc, i+1) for i in range(len(abc)) if i % 3 == 0 and i < 24]
data = []
for i, o in enumerate(lists):
curr = [0]*len(lists)
for obj in list(o):
curr[i] = obj
data.append(curr.copy())
pprint(data)
或者,如果您想找点乐子,这里是单线:
data = [(lambda l, ind, obj: l[:ind] + [obj] + l[ind+1:])([0]*len(lists), i, letter) for i,o in enumerate(lists) for letter in list(o)]
这是一个自封装的代码,它可以一行完成一切(包括生成字符串和打印内容)(请不要使用它-只是为了好玩):
print((lambda lists: [(lambda l, ind, obj: l[:ind] + [obj] + l[ind+1:])([0]*len(lists), i, letter) for i,o in enumerate(lists) for letter in list(o)])([(lambda l, i: f"{l[i-1]}{l[i]}{l[i+1]}")("abcdefghijklmnopqrstuvwxyz", i+1) for i in range(len("abcdefghijklmnopqrstuvwxyz")) if i % 3 == 0 and i < 24]))
输出
[['a', 0, 0, 0, 0, 0, 0, 0],
['b', 0, 0, 0, 0, 0, 0, 0],
['c', 0, 0, 0, 0, 0, 0, 0],
[0, 'd', 0, 0, 0, 0, 0, 0],
[0, 'e', 0, 0, 0, 0, 0, 0],
[0, 'f', 0, 0, 0, 0, 0, 0],
[0, 0, 'g', 0, 0, 0, 0, 0],
[0, 0, 'h', 0, 0, 0, 0, 0],
[0, 0, 'i', 0, 0, 0, 0, 0],
[0, 0, 0, 'j', 0, 0, 0, 0],
[0, 0, 0, 'k', 0, 0, 0, 0],
[0, 0, 0, 'l', 0, 0, 0, 0],
[0, 0, 0, 0, 'm', 0, 0, 0],
[0, 0, 0, 0, 'n', 0, 0, 0],
[0, 0, 0, 0, 'o', 0, 0, 0],
[0, 0, 0, 0, 0, 'p', 0, 0],
[0, 0, 0, 0, 0, 'q', 0, 0],
[0, 0, 0, 0, 0, 'r', 0, 0],
[0, 0, 0, 0, 0, 0, 's', 0],
[0, 0, 0, 0, 0, 0, 't', 0],
[0, 0, 0, 0, 0, 0, 'u', 0],
[0, 0, 0, 0, 0, 0, 0, 'v'],
[0, 0, 0, 0, 0, 0, 0, 'w'],
[0, 0, 0, 0, 0, 0, 0, 'x']]
答案 2 :(得分:0)
首先,我将这些列表加在一起,就像这样:
lists = [list_1, list_2, list3...]
现在您可以创建一个嵌套数组:
output = []
for i in range(0, len(list)):
for letter in list:
#initialize array to be appended to output.
temp = [0, 0, 0, 0, 0, 0, 0, 0]
#replace index i with letter
temp[i] = letter
#add it to the output
output.append(temp)