python - 我怎样才能洗牌我从 Postgresql 得到的结果?

标签 python postgresql

我在 python 脚本中使用 psycopg2:

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

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

更新:

行数约为 50.000

最佳答案

如果计数不是很大,你可以使用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

关于python - 我怎样才能洗牌我从 Postgresql 得到的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41218369/

相关文章:

java - 将 jar 输出通过管道传输到 python 中的文件

python - 在所有驱动器中搜索一个文件

database - PostgreSQL : how to delete rows of Table1 where category = x (but Category is defined in Table 2)?

java - sql(postgres)- 如何创建一个触发器,将表中的两行相乘并将它们添加到另一个表中的一行?

Postgresql 外部表存在子句

python - Tkinter 摧毁 Toplevel

python - 在 MacOS 上清理和管理 Python 版本

python - 从图像中读取文本的 OCR 库(最好是 python)

postgresql - 在 PostgreSQL 9.0 中破坏的 Anorm 使用 Order By 选择?

json - PostgreSQL:比较 json