如何迭代此列表以创建矩阵?

时间:2018-10-05 05:21:25

标签: python arrays for-loop

在在线课程中,练习的一部分是创建矩阵。

我们获得了以下数据:

KobeBryant_FT = [696,667,623,483,439,483,381,525,18,196]
JoeJohnson_FT = [261,235,316,299,220,195,158,132,159,141]
LeBronJames_FT = [601,489,549,594,593,503,387,403,439,375]
CarmeloAnthony_FT = [573,459,464,371,508,507,295,425,459,189]
DwightHoward_FT = [356,390,529,504,483,546,281,355,349,143]
ChrisBosh_FT = [474,463,472,504,470,384,229,241,223,179]
ChrisPaul_FT = [394,292,332,455,161,337,260,286,295,289]
KevinDurant_FT = [209,209,391,452,756,594,431,679,703,146]
DerrickRose_FT = [146,146,146,197,259,476,194,0,27,152]
DwayneWade_FT = [629,432,354,590,534,494,235,308,189,284]

为了创建矩阵,这将是代码:

FT = np.array([KobeBryant_FT, JoeJohnson_FT, LeBronJames_FT, 
               CarmeloAnthony_FT, DwightHoward_FT, ChrisBosh_FT, ChrisPaul_FT,
               KevinDurant_FT, DerrickRose_FT, DwayneWade_FT])

我想知道是否有一种方法可以使用“ for”循环来模拟上述代码的输出,而无需手动键入KobeBryant_FT,JoeJohnson_FT,LeBronJames_FT等。

3 个答案:

答案 0 :(得分:1)

这取决于您如何接收此数据。如果它位于* .txt文件中,那么您可以读取它line by line(如果您想与列表同时分配名称),或者一次读取所有内容,然后使用regular expression用于方括号内的任何内容。

import re

file = open("data.txt","r").read()

lists_txt = re.finditer('[\[].*[\]]$', file, flags=re.MULTILINE)
#item in lists_txt = anything found inside [] brackets.

for item in lists_txt:
    txt = str(item.group(0))
    print(txt[1:-1])

程序输出:

696,667,623,483,439,483,381,525,18,196
261,235,316,299,220,195,158,132,159,141
601,489,549,594,593,503,387,403,439,375
573,459,464,371,508,507,295,425,459,189
356,390,529,504,483,546,281,355,349,143
474,463,472,504,470,384,229,241,223,179
394,292,332,455,161,337,260,286,295,289
209,209,391,452,756,594,431,679,703,146
146,146,146,197,259,476,194,0,27,152
629,432,354,590,534,494,235,308,189,284

您应该在[]中获得任何字符串。现在,通过using .split(","),您可以将它们转换为列表。

希望它能帮助您:)

答案 1 :(得分:0)

尝试一下

import pandas as pd
df = pd.DataFrame(FT)

答案 2 :(得分:0)

创建列表时,可以将它们放入字典中,以便可以更轻松地引用它们:

d = {"KB":[696,667,623,483,439,483,381,525,18,196], "JJ":[261,235,316,299,220,195,158,132,159,141]}
np.stack(d.values())
# Out[32]: 
# array([[261, 235, 316, 299, 220, 195, 158, 132, 159, 141],
#        [696, 667, 623, 483, 439, 483, 381, 525,  18, 196]])

如果要按特定顺序排列数组,可以使用Ordereddict:

from collections import OrderedDict
d = OrderedDict({"KB":[696,667,623,483,439,483,381,525,18,196], "JJ":[261,235,316,299,220,195,158,132,159,141]})
np.stack(d.values())