[‘AC’, ‘2H’, ‘3S’, ‘4C’]
How do I check if the 1st index (eg 2nd element) of every string occurs more than once? For example, in this case, C occurs 2 times so I need to return False This must apply to other case as well such as H or S occuring more than once
Consider using collections.Counter
to count the occurrences of interested items. And use all
or any
to verify the condition.
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)
You can use this 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
This returns how many times it happens, if you just want to see if it exists:
def check_amount(all_text, character):
for text in all_text:
for ch in text:
if ch == character:
return True
else:
return False
Those are for checking at any position this is if you need it to be at a specific position like you said:
def check_amount(all_text, character):
count = 0
for text in all_text:
if text[1] == character:
count += 1
return count
And then you can change this if you want the boolean version using the same method of not using the count
The all_text
is the list you want to pass in, and the character
you want to see if is there/exists.
Using regular expressions, you can use re.finditer
to find all (non-overlapping) occurences:
>>> 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
Alternatively, if you don't want the overhead of regular expressions, you can also repeatedly use str.find to get the next index:
>>> 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.
for an array here I'd use List Comprehension, like this:
listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test', 'Ok']
now let's find all indexes of 'ok' in the list
# 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.