带列表变量的查询

krcsximq  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(251)

我列了一个id的列表,每个值都是int类型

  1. temp_id = [7922, 7018, 5650, 209, 21928, 2294, 10507, 3623]
  2. type(tempasn)
  3. list

这样做有效:

  1. Temp = pd.read_sql("select count(*) as count\
  2. from "+db+"\
  3. where ids in (7922, 7018, 5650, 209, 21928, 2294, 10507, 3623)\
  4. order by count desc limit 10", conn)

我想把列表中的变量添加到我的查询中
这会导致错误

  1. Temp = pd.read_sql("select count(*) as count\
  2. from "+db+"\
  3. where ids in "+temp_id+"\
  4. order by count desc limit 10", conn)
  5. TypeError: Can't convert 'list' object to str implicitly

我不明白我需要改变什么
回答
最终采纳了下面的评论并修改了生成临时ID的循环:

  1. temp_id = []
  2. for id in df['ID']:
  3. if id and id not in temp_id:
  4. temp_id.append(str(ID))
  5. #Convert to list format
  6. temp_id = ", ".join(temp_id)

有两件事让这件事成功了:

  1. str(ID) & temp_id = ", ".join(temp_id)
nkoocmlb

nkoocmlb1#

您需要将变量存储为逗号分隔的字符串,而不是数组。
所以声明temp\u id为string。

  1. temp_id = "7922, 7018, 5650, 209, 21928, 2294, 10507, 3623"
  2. Temp = pd.read_sql("select count(*) as count\
  3. from "+db+"\
  4. where ids in ("+temp_id+")\
  5. order by count desc limit 10", conn)
8dtrkrch

8dtrkrch2#

你需要一个字符串,所以你应该内爆你的数组

  1. temp_id = [7922, 7018, 5650, 209, 21928, 2294, 10507, 3623]
  2. my_string = ",".join(temp_id )
  3. Temp = pd.read_sql("select count(*) as count\
  4. from "+db+"\
  5. where ids in ("+my_string+")\
  6. order by count desc limit 10", conn)

相关问题