簡體   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