我如何检查每个字符串的2个项目是否多次出现

时间:2020-05-22 14:02:13

标签: python string list iteration

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

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

3 个答案:

答案 0 :(得分:1)

请考虑使用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)

答案 1 :(得分:0)

您可以使用此功能:

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

这些都是用于检查任何位置的,如果您需要将其放在特定位置,如您所说:

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

然后,如果要使用不使用计数的相同方法来获取布尔版本,则可以更改此值

all_text是您要传递的列表,而character是您要查看的列表/是否存在。

答案 2 :(得分:0)

使用正则表达式,您可以使用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.

对于这里的数组,我将使用列表推导,如下所示:

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)

输出:

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