比较python 3.4中未标记列表/矩阵列表的特定元素
我从一个大数据文件中创建了一长串列表,现在看起来像这样:比较python 3.4中未标记列表/矩阵列表的特定元素,python,list,compare,Python,List,Compare,我从一个大数据文件中创建了一长串列表,现在看起来像这样: [[1, -1, 10, 0]] [[2, 1, 20, 5]] [[3, 2, 15, 10], [4, 2, 50, 10], [5, 2, 90, 10]] [[6, 3, 15, 11]] [[7, 4, 50, 11]] [[8, 5, 90, 11]] [[9, 6, 13, 14]] [[10, 7, 50, 14]] [[11, 8, 70, 14], [12, 8, 95, 14], [13, 8, 75, 14]]..
[[1, -1, 10, 0]]
[[2, 1, 20, 5]]
[[3, 2, 15, 10], [4, 2, 50, 10], [5, 2, 90, 10]]
[[6, 3, 15, 11]]
[[7, 4, 50, 11]]
[[8, 5, 90, 11]]
[[9, 6, 13, 14]]
[[10, 7, 50, 14]]
[[11, 8, 70, 14], [12, 8, 95, 14], [13, 8, 75, 14]].....
使用此代码
import csv
import operator
import itertools
with open('data.txt', 'r') as f:
csv_input = csv.reader(f, delimiter=' ', skipinitialspace=True)
headers = next(csv_input)
for k, g in itertools.groupby(csv_input, key=operator.itemgetter(3)):
row = []
for entry in g:
entry = [float(e) for e in entry]
row.append(entry)
print(row)
现在,我想比较第一个列表[1,-1,10,0]中的第一个值,即1,与下一个列表第一行中的第二个值,即1。然后,我想比较第二个列表第一行的第一个值,即2,与下一个列表的第一行,下一个列表的第二行,然后是第三个。等等
我知道synax可能很糟糕,但我想到的是一个代码,类似于上面代码的续行:
#save list of lists
with open("matrices.csv", "wb") as d:
writer = csv.writer(d)
def listCompare():
lists = d
i=1
if list[i][0] == list[i+1][1]:
return True
else list[i][0] != list[i+1][1]: #***
return False
i+1
continue
有人知道我该怎么做吗?从其他类似于我的问题来看,大多数人都将变量分配给每个列表,这是唯一的方法吗
***这一行的语法无效
提前感谢您的帮助 出现无效语法错误的原因是else语句不带条件。因此,在您的情况下,您目前有:
if list[i][0] == list[i+1][1]:
return True
else list[i][0] != list[i+1][1]: #problem line
return False
这应该是:
if list[i][0] == list[i+1][1]:
return True
else:
return False
或者如果您想检查另一种情况:
if list[i][0] == list[i+1][1]:
return True
elif (condition goes here):
do something
else:
return False
但是,正如@Alexander Trakhimenok在评论中所说,你甚至不需要这个if-else语句
return list[i][0] == list[i+1][1]
现在,看一下你的代码中的几个指针
函数listCompare不带参数,然后你想让lists=d,我猜这只是在这个问题上被误解了。您可能希望将d作为参数传递。此外,list是一个糟糕的变量名,我认为它可能只是列表的一个输入错误
另外,我不确定您为什么要使用I或continue,因为现在在修复语法内容之后,您的代码相当于:
def listCompare(d):
return d[1][0] == d[2][1]
不需要if-else,只需返回list[i][0]==list[i+1][1]