我有一个如下列表
int[] newList1 = Arrays.copyOf(increments, increments.length);
我有一个基于列表生成的序列:
mylist = ['f', 'i', 'r', 's', 't', ' ', 'r', 'a', 'y', ' ', '>', ' ', 's', 'a', 'n', 'k', 'r', 'i', 't', ' ', '>', ' ', 'f', 'e', 'm', 'a', 'l', 'e', ' ', '>', ' ', ' ', '=', ' ', 'a', 'a', 'd', 'h', 'y', 'a', '\n', 'u', 'n', 'i', 'q', 'u', 'e', ' ', '>', ' ', 's', 'a', 'n', 'k', 'r', 'i', 't', ' ', '>', ' ', 'm', 'a', 'l', 'e', ' ', '>', ' ', ' ', '=', ' ', 'a', 'd', 'h', 'v', 'a', 'i', 't', 'h']
它生成
sequence = np.arange(0, len(mylist) - 11, 3)
我的输出是一个二维列表
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66]
最终输出列表应如下所示:
loop on the sequence
dimension1= mylist[sequence:sequence+11]
dimension2 = mylist[sequence+12]
我想在不编写for循环的情况下生成此文件。我可以在R中进行如下操作
dimension1 dimension2
"f" "i" "r" "s" "t" " " "r" "a" "y" " " ">" " " "s"
"s" "t" " " "r" "a" "y" " " ">" " " "s" "a" "n" "s"
"r" "a" "y" " " ">" " " "s" "a" "n" "s" "k" "r" "i"
`
有人可以帮我将上述R代码翻译成Python
答案 0 :(得分:1)
我们可以初始化字典并向其添加值
import pandas as pd
maxlen = 12
dictN = {'dimension1':[], 'dimension2':[]}
mlenN = maxlen - 1
for i in range(0, len(mylist) - mlenN, 3):
dictN['dimension1'].append(mylist[i:(i+mlenN)])
dictN['dimension2'].append(mylist[i + maxlen-1])
pd.DataFrame(dictN)
或者如评论中提到的@Parfait一样,它可以写成字典理解
maxlen = 12
mlenN = maxlen - 1
dictN = [{'dimension1':mylist[i:(i+mlenN)], \
'dimension2':mylist[i + maxlen-1]} \
for i in range(0, len(mylist) - mlenN, 3)]