如何从Python的两个列表中创建带有标签的二维数组(没有numpy或pandas)?
假设我有五个石头、布、剪刀游戏的分数,看起来像这样:如何从Python的两个列表中创建带有标签的二维数组(没有numpy或pandas)?,python,arrays,2d,Python,Arrays,2d,假设我有五个石头、布、剪刀游戏的分数,看起来像这样: player_score = [1,0,1,1,0] cpu_score = [0,1,0,0,1] class ScoreBoard: def __init__(self): self.player_score = [1,0,1,1,0] self.cpu_score = [0,1,0,0,1] def __str__(self): string = '\t'
player_score = [1,0,1,1,0]
cpu_score = [0,1,0,0,1]
class ScoreBoard:
def __init__(self):
self.player_score = [1,0,1,1,0]
self.cpu_score = [0,1,0,0,1]
def __str__(self):
string = '\t'
for i in range(len(self.player_score)):
string += 'G%d '%(i+1)
string = string + '\n\nPlayer\t'
for i in range(len(self.player_score)):
string += '%d '%self.player_score[i]
string = string + '\nCPU\t'
for i in range(len(self.cpu_score)):
string += '%d '%self.cpu_score[i]
return string
def record_score(self, player_score, cpu_score):
self.player_score.append(player_score)
self.cpu_score.append(cpu_score)
我想制作一个2d数组(没有numpy或pandas),用来记录玩过的游戏(比如记分牌)。因此,最终输出将看起来像这样:
G1 G2 G3 G4 G5
Player 1 0 1 1 0
CPU 0 1 0 0 1
有什么建议吗?我想你想要的是数据帧
import pandas as pd
player_score = [1,0,1,1,0]
cpu_score = [0,1,0,0,1]
df = pd.DataFrame([player_score, cpu_score])
df.columns = ["G1", "G2", "G3", "G4", "G5"]
df.index = ['Player', 'CPU']
print(df)
给予
Numpy和pandas是Python编程中的强大工具,但尝试在没有它们的情况下工作有助于更好地学习。它们提供了多种有用的函数和对象类,如果没有这些函数和对象类,您可能需要定义自己的函数和对象类 要显示您想要的记分板,我建议您定义自己的记分板类。我给你举一个这样的例子:
player_score = [1,0,1,1,0]
cpu_score = [0,1,0,0,1]
class ScoreBoard:
def __init__(self):
self.player_score = [1,0,1,1,0]
self.cpu_score = [0,1,0,0,1]
def __str__(self):
string = '\t'
for i in range(len(self.player_score)):
string += 'G%d '%(i+1)
string = string + '\n\nPlayer\t'
for i in range(len(self.player_score)):
string += '%d '%self.player_score[i]
string = string + '\nCPU\t'
for i in range(len(self.cpu_score)):
string += '%d '%self.cpu_score[i]
return string
def record_score(self, player_score, cpu_score):
self.player_score.append(player_score)
self.cpu_score.append(cpu_score)
如果你
a = ScoreBoard()
print(a)
a.record_score(1, 0)
print(a)
,这将显示:
G1 G2 G3 G4 G5
Player 1 0 1 1 0
CPU 0 1 0 0 1
G1 G2 G3 G4 G5 G6
Player 1 0 1 1 0 1
CPU 0 1 0 0 1 0
显然,要使这门课学好,还需要做更多的工作
1) 最初的玩家分数和cpu分数必须为[]
2) 如果记分牌是空的怎么办?当它为空时,您会装饰字符串输出吗
3) 有没有可能是平局,就像摇滚对摇滚?如果没有,当您有玩家分数时,可以计算cpu分数。在这种情况下,这两个选项中的一个是不必要的
4) 也许它可以成为更多比赛的记分牌,那里有更多的球员
5) 也许您甚至可以定义自己的标签2D数组,比如pandas.DataFrame
import pandas as pd
player_score = [1,0,1,1,0]
cpu_score = [0,1,0,0,1]
df = pd.DataFrame([player_score, cpu_score])
df.columns = ["G1", "G2", "G3", "G4", "G5"]
df.index = ['Player', 'CPU']
print(df)
如果您还没有学习Python中的对象或接口编程,您可以自由提问。您还可以在中了解更多信息。我的答案有效吗?否(我更新了我的问题,忘记了熊猫)我得到:回溯(上次的最新调用):文件“****************************”,第11行,在导入熊猫作为pd模块中无错误:没有名为“熊猫”的模块您没有指定任何内容。标签是什么?你想要的行为是什么?您显示的输出没有回答这些问题。照目前情况看,你的问题不清楚/范围太广