比较字符串列表并获取它们之间的第一个匹配字符列表(Python)

2024-06-25 22:55:36 发布

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

如果我有一个这样的数字数组,我需要它来打印“1”,因为它是比较每个字符串时最早的匹配字符

Numbers = ["590", "390", "160", "170", "170"]

运行我在下面编写的代码会得到数字“2”,因为它是第一个匹配字符。那是我能做的最远的事了,我不知道该怎么办了。你知道吗

import itertools
import math

qw = "5234"
qe = "4211"
match = list(set(qw.lower()) & set(qe.lower()))
minPoint = match.index(min(match))
match[minPoint]

Tags: 字符串代码importmatch数字math数组字符
1条回答
网友
1楼 · 发布于 2024-06-25 22:55:36

你的set想法是正确的,但是你可能想先zip,因为这将你想要比较的数字分组在一起。 最方便的方法是使用collections.Counter

import collections

for j, row in enumerate(zip(*Numbers)):
    counts = collections.Counter(row)
    best = counts.most_common(1)[0]
    if best[1] > 1:
        print("Found {} occurrences of {} in position {}".format(best[1], best[0], j))
        break
else:
    print('No repeats found')

相关问题 更多 >