python - 如何在mysql中搜索有多少重复项并进行比较

标签 python python-3.x mysql-python

所以我想比较变量 a和变量b基于它们在 mysql 中有多少重复项。这是我的代码:

query = """ SELECT `do` FROM `foo` """
cursor.execute(query)
result=cursor.fetchall()

a = '0001'
b = '1100'
y = collections.Counter(result)
print(y)

这是我的输出:

Counter({('0001',): 2, ('1100',): 1}, ('0000',): 4})

输出正在计算整行的重复项。我希望它只计算多少 ab在mysql中。

我实际上不知道此后该做什么。我希望代码运行
if a > b打印a
如果a < b打印b

我想要的输出:

a = 2 # number of duplicates
b = 1
a # print a because a > b

任何答案将不胜感激。

最佳答案

a = ("0001",)  # Set to tuples so you can directly use them as keys
b = ("1100",)

y = Counter({('0001',): 2, ('1100',): 1, ('0000',): 4})

a_count = y.get(a)  # The number of times `("0001",)` occurs
b_count = y.get(b)  # The number of times `("1100",)` occurs

if a_count > b_count:
    print(a)
elif a_count < b_count:
    print(b)

关于python - 如何在mysql中搜索有多少重复项并进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57748306/

相关文章:

python - MySQLdb Python 执行不返回表

python - Opencv或Numpy-有效替换图像中的像素列表

python-3.x - 如何在并行化随机种子实验时确保可重复性?

linux - 安装供应商程序-libpython3.so : cannot open shared object file

python - 使用 MySQLdb for Python 时如何使用选项 skip-name-resolve?

python - 如何解决这个 Django/MySQL 设置灾难?

python - Pygame:允许点击穿过窗口

python - 在二维中创建两个 Pandas 数据框的组合

python - RegEx 忽略注释行。

python - 我不理解 python 中的 sum(iterable[, start])