我正在参与棒球项目,我试图将来自两个不同csv文件的运动员名字与相应的统计数据进行匹配
例如,我有两个列表,如下所示:
player_stats1 = [[Clayton Kershaw, stats, more stats, more stats]]
player_stats2 = [[Clayton Kershaw, stats, more stats, more stats]]
我有一个if语句,检查这两个名字是否相同
if player_stats1[1][1] and player_stats1[1][2] == player_stats2[1][1] and player_stats2[1][2]:
print('True')
else:
print('false')
我需要检查名称是否相同以及是否附加players_stats2[1][0] and players_stats2[1][5] to the original list, players_stats1
我已经尝试了
length1 = len(player_stats1)
players_stats3 = []
i = 1
while i < length1:
if player_stats1[1][i] and player_stats1[1][i + 1] == player_stats2[1][i] and player_stats2[1][i + 1]:
players_stats3.append(player_stats2[i][0], player_stats2[i][5])
else:
print('')
i += 1
但我一直收到错误。
IndexError: list index out of range
答案 0 :(得分:1)
您有一份清单清单。所以改变你的索引方式。
# get the i-th list of player stats | [Clayton Kershaw, stats, more stats, more stats]
player_stats1[i]
# get the name in the i-th list of player stats
player_stats1[i][1]
在示例中,您将玩家名称作为第一个项目,如果这是正确的,则应该使用以下内容来获取名称。
player_stats1[i][0]
实施例
>>> lsts = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
>>> lsts[0][1] # first list, second item
2
您的原始if语句也存在问题。
if player_stats1[1][1] and player_stats1[1][2] == player_stats2[1][1] and player_stats2[1][2]:
print('True')
else:
print('false')
如果您的列表中包含&#34; truthy&#34;这将始终打印为True。值。你需要比较两者。
player_stats1[1][1] == player_stats2[1][1] and player_stats1[1][2] == player_stats2[1][2]
备选方案:
您还可以使用zip
将列表组合在一起并同时迭代这两个列表。
player_stats1 = [ ["A", "B"], ["A", "C"], ["D", "A"], ["E", "E"]]
player_stats2 = [ ["A", "A"], ["D", "A"], ["A", "C"], ["E", "E"]]
res = []
for p1, p2 in zip(player_stats1, player_stats2):
if p1[0] == p2[0] and p1[1] == p2[1]:
res.append( (p2[0], p2[1]) )
print(res)
zip
的缺点是:
如果你想找到所有匹配项,那么你需要循环比较它们。
res = []
for p2 in player_stats1:
for p1 in player_stats2:
if p1[0] == p2[0] and p1[1] == p2[1]:
res.append( (p2[0], p2[1]) )
print(res)
答案 1 :(得分:0)
更改var Requests = {
get: function(search) {
return new Promise(function(resolve, reject){
// call resolve in case of success, and reject in case of error
})
}
}
Requests.get('thing').then(
function(response){
// success
},
function(error){
// something went wrong
}
);
:因为长度为4,但您的列表索引最多为while i < length1 -1
答案 2 :(得分:0)
你有
static void Sort(JObject jObj)
{
var props = jObj.Properties().ToList();
foreach (var prop in props)
{
prop.Remove();
}
foreach (var prop in props.OrderBy(p => p.Name))
{
jObj.Add(prop);
if (prop.Value is JObject)
Sort((JObject)prop.Value);
if (prop.Value is JArray)
{
Int32 iCount = prop.Value.Count();
for (Int32 iIterator = 0; iIterator < iCount; iIterator++)
if (prop.Value[iIterator] is JObject)
Sort((JObject)prop.Value[iIterator]);
}
}
}
然后使用:
length1 = len(player_stats1)
你怎么知道player_stats1 [1] [i]存在?
你不应该:
player_stats1[1][i]
其他:
length1 = len(player_stats1[1])
这假设player_stats1和player_stats2的长度相同。但总的来说,这似乎是错误的解决方案。 你应该从一个csv创建一个键/值对,并检查另一个,因为在这个解决方案中,如果你有一个错误顺序的匹配玩家,你将无法找到它。