how to compare the rows of a table using python

强颜欢笑 提交于 2019-12-11 11:55:17

问题


Sorry if the title was misleading or not very descriptive, but here is what I want I have a table with 2 columns :

name|value
1.aaaa|132412
2.aaaa|234124
3.aaaa|542253
bbbb|234324
bbbb|342342

so I want to basically compare the rows where name="aaaa" the part where I am stuck is how do I compare all the rows with name="aaaa"

sql="select value from table where name='aaaa'"
cursor.execute(sql)
result=cursor.fetchall()
for row in result:
  value=row[0]

how do I go about from here ?

edit: I want to compare value of 1 with 2,1 with 3 and similarly 2 with 3 and so on..


回答1:


You've figured out the code to get all the results, and then it sounds like you want to compare all the two-item combinations of values.

sql="select value from table where name='aaaa'"
cursor.execute(sql)
results=cursor.fetchall() # changed to results to better reflect the list structure
count = len(results)
for i in range(0, count):
  for j in range (i+1, count):
    print results[i][0], results[j][0]

That'll print all the pairs . . . obviously you'll want to parse them instead, and do your comparisons where the print statement is.



来源:https://stackoverflow.com/questions/11659513/how-to-compare-the-rows-of-a-table-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!