【问题标题】:Comparing a list of strings to itself and getting a list of the first matching characters between them (Python)将字符串列表与其自身进行比较并获取它们之间的第一个匹配字符的列表(Python)
【发布时间】:2017-09-12 17:44:13
【问题描述】:

如果我有一个这样的数字数组,我需要它打印“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]

【问题讨论】:

标签: python list matching


【解决方案1】:

您的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')

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 2014-01-05
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    相关资源
    最近更新 更多