I want to sort an array containing tuples from a sql query based on a particular attribute. I have a table like this:
我希望根据特定的属性从sql查询中对包含元组的数组进行排序。我有一张这样的桌子:
+-----+------------+-----------+
| lid | name | num |
+-----+------------+-----------+
| 2 | Ruby's | 0 |
| 3 | Five Guy's | 1 |
| 4 | Habana's | 0 |
+-----+------------+-----------+
and I want to print out names based on their num attribute AKA I want the output to be:
我想打印出基于它们的num属性的名字我想输出是:
Five Guy's
Ruby's
Habana's
I am attempting to accomplish that with this:
我正试图通过以下方式实现这一点:
...
data = cursor.fetchall()
...
def getKey(name):
return name['num']
sorted(data, key=getKey)
for row in data:
print row['name']
but this outputs the data in the order:
但这按顺序输出数据:
Ruby's
Five Guy's
Habana's
I'm very to new to python and I am just trying to mess round with some things so please let me know if there are any glaring issues
我对python很陌生,我只是想把一些东西弄乱,如果有什么明显的问题,请告诉我
I am running python=2.7.10
我运行python = 2.7.10
2 个解决方案
#1
2
for row in sorted(data, key=getKey):
print row['name']
#2
2
Your issue is that sorted()
returns a new sorted copy of the list. If you want to sort ion place use data.sort(key=getKey)
(if data
is a list).You would need to save the return value of sorted()
to something to use it properly:
您的问题是sort()返回列表的一个新的排序副本。如果您想对离子位置进行排序,请使用data.sort(key=getKey)(如果数据是列表)。您需要将sort()的返回值保存到适当使用它的对象:
...
data = cursor.fetchall()
...
def getKey(name):
return name['num']
sorted_data = sorted(data, key=getKey)
for row in sorted_data:
print row['name']
#1
2
for row in sorted(data, key=getKey):
print row['name']
#2
2
Your issue is that sorted()
returns a new sorted copy of the list. If you want to sort ion place use data.sort(key=getKey)
(if data
is a list).You would need to save the return value of sorted()
to something to use it properly:
您的问题是sort()返回列表的一个新的排序副本。如果您想对离子位置进行排序,请使用data.sort(key=getKey)(如果数据是列表)。您需要将sort()的返回值保存到适当使用它的对象:
...
data = cursor.fetchall()
...
def getKey(name):
return name['num']
sorted_data = sorted(data, key=getKey)
for row in sorted_data:
print row['name']