sqlite 计算字符串出现的次数

hgb9j2n6  于 2022-12-13  发布在  SQLite
关注(0)|答案(1)|浏览(221)

我正在计算一个品牌出现的次数,我研究了很多,发现可能需要使用count(),但是我如何应用到这种情况呢?

favourites = conn.execute('SELECT Favourite.id, Favourite.smartphoneID, Smartphone.brand, Smartphone.model, Smartphone.lowprice, Smartphone.highprice, Smartphone.image_URL FROM Favourite INNER JOIN Smartphone ON Favourite.userID = ? AND Favourite.smartphoneID = Smartphone.id',(userid)).fetchall()
for favourite in favourites:
    print(favourite[2])

根据下面的输出,我的预期结果是Apple计数应为2,Samsung应为1

127.0.0.1 - - [07/Dec/2022 19:12:54] "GET /static/smartphone.css HTTP/1.1" 304 -
127.0.0.1 - - [07/Dec/2022 19:12:54] "GET /static/iphone13.webp HTTP/1.1" 304 -
Apple
Samsung
Apple
127.0.0.1 - - [07/Dec/2022 19:13:00] "GET /favourite HTTP/1.1" 200 -
127.0.0.1 - - [07/Dec/2022 19:13:00] "GET /static/smartphone.css HTTP/1.1" 304 -
127.0.0.1 - - [07/Dec/2022 19:13:00] "GET /static/iphone14.jpg HTTP/1.1" 304 -
127.0.0.1 - - [07/Dec/2022 19:13:00] "GET /static/samsung-galaxy-S21-5G.jpg HTTP/1.1" 304 -
127.0.0.1 - - [07/Dec/2022 19:13:00] "GET /static/iphone13.webp HTTP/1.1" 304 -
lx0bsm1f

lx0bsm1f1#

实际上你解决了这个问题,但停留在一个简单的地方:)
让我向您展示如何计算列表中的所有字段;

sample_list = ["apple", "apple", "Samsung"]

counts = {key:sample_list.count(key) for key in set(sample_list)}
print(counts)

# output: {"apple": 2, "Samsung": 1}

相关问题