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

我们得到以下数据:

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等。

最佳答案

这取决于您如何接收此数据。如果它在* .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(",")可以将它们转换为列表。

希望它可以帮助您:)

关于python - 如何迭代此列表以创建矩阵?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52658793/

10-08 22:50