如何对Postgresql得到的结果进行洗牌?

2024-04-20 09:42:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python脚本中使用psycopg2:

  conn = psycopg2.connect(......)
  cur = conn.cursor()
  cur.execute("select * from table1")
  rows = cur.fetchall()
  for a1 in rows: # how to shuffle them?

我希望每次检索行时它们的顺序都不同。我怎么能做到呢?在

更新

行数大约为50000行


Tags: infrom脚本forexecutea1connectconn
1条回答
网友
1楼 · 发布于 2024-04-20 09:42:30

如果计数不多,可以使用random.shuffle

from random import shuffle

...

rows = list(cur.fetchall())
shuffle(rows)
# do what you need with the suffled rows

否则,您可以随机选择项目。在Postgres中有很多方法可以做到:

1)Best way to select random rows PostgreSQL

2)quick random row selection in Postgres

相关问题 更多 >