繁体   English   中英

我如何检查每个字符串的 2 项是否不止一次出现

[英]How do i check the 2 item of every string for more than one occurence

[‘AC’, ‘2H’, ‘3S’, ‘4C’]

如何检查每个字符串的第一个索引(例如第二个元素)是否多次出现? 例如,在这种情况下,C 出现了 2 次,所以我需要返回 False 这也必须适用于其他情况,例如 H 或 S 出现多次

考虑使用collections.Counter来计算感兴趣项目的出现次数。 并使用allany来验证条件。

import collections

a = ['AC', '2H', '3S', '4C']
counter = collections.Counter(s[1] for s in a)
result = all(v < 2 for v in counter.values())

print(result)

您可以使用这个 function:

def check_amount(all_text, character):
    count = 0
    for text in all_text:
        for ch in text:
            if ch == character:
                count += 1
    return count

如果您只想查看它是否存在,这将返回它发生的次数:

def check_amount(all_text, character):
    for text in all_text:
        for ch in text:
            if ch == character:
                return True
            else:
                return False

这些用于在任何 position 进行检查,如果您需要它位于特定的 position 上,就像您说的那样:

def check_amount(all_text, character):
    count = 0
    for text in all_text:
        if text[1] == character:
            count += 1
    return count

然后,如果您想要 boolean 版本,则可以使用不使用计数的相同方法进行更改

all_text是您要传入的列表,以及您要查看的character是否存在/存在。

使用正则表达式,您可以使用re.finditer查找所有(非重叠)出现:

>>> import re
>>> text = 'Allowed Hello Hollow'
>>> for m in re.finditer('ll', text):
         print('ll found', m.start(), m.end())

ll found 1 3
ll found 10 12
ll found 16 18

或者,如果你不想要正则表达式的开销,你也可以重复使用 str.find 来获取下一个索引:

>>> text = 'Allowed Hello Hollow'
>>> index = 0
>>> while index < len(text):
        index = text.find('ll', index)
        if index == -1:
            break
        print('ll found at', index)
        index += 2 # +2 because len('ll') == 2

ll found at  1
ll found at  10
ll found at  16
This also works for lists and other sequences.

对于此处的数组,我将使用 List Comprehension,如下所示:

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']

现在让我们在列表中找到所有 'ok' 的索引

# Use List Comprehension Get indexes of all occurrences of 'Ok' in the list
indexPosList = [ i for i in range(len(listOfElems)) if listOfElems[i] == 'Ok' ]

print('Indexes of all occurrences of "Ok" in the list are: ', indexPosList)

output:

Indexes of all occurrences of "Ok" in the list are :  [1, 3, 9]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM