简体   繁体   English

需要计算if语句中给定字符串的出现次数

[英]need to count number of occurrences of given strings in an if statement

so in my function one of my if statements is that the string does not have more than 1 occurrence of a string that is in a list. 所以在我的函数中,我的一个if语句是字符串在列表中没有多于1次出现的字符串。

for example: 例如:

list = ['a','b']

i need to check if a string has more than one of those 2 characters in it or else it will move on to the next if statement. 我需要检查字符串中是否包含多个这两个字符,否则它将转到下一个if语句。

s = 'aloha'

s will pass the if statement because b is not in s. s将传递if语句,因为b不在s中。

s = 'abcd'

s should fail this if statement because both a and b are in s. s应该使if语句失败,因为a和b都在s中。

more examples if it's not clear enough. 更多的例子,如果它不够清楚。

s = 'aaab'

this will fail the if statement and move on. 这将失败if语句并继续前进。

s = 'aaloh'

this will also fail 这也将失败

my if statement was: 我的if语句是:

if s.count('a') == 1 or s.count('b') == 1:

This if statement doesn't work 这个if语句不起作用

my question is, is there a way to check this without doing a for loop before hand? 我的问题是,有没有办法检查这个没有事先做一个for循环?

You'll need a for loop, but you can still do it one line. 你需要一个for循环,但你仍然可以做一行。

if sum(char in s for char in list) > 1:

If you wanted to look for specific numbers of a given character with some threshold, put your list of characters into a dict like d = {'a': 1, 'b': 4} . 如果您想要查找具有某个阈值的给定角色的特定数字,请将您的角色列表放入d = {'a': 1, 'b': 4}类的dict

if sum(s.count(char) >= count for char, count in d.items) > THRESHOLD:

Update 更新

The OP commented that he wants a OP评论说他想要一个

a function that does something with the string if and only if that string doesn't have both 'a' and 'b' in the string. 当且仅当字符串在字符串中不同时具有'a'和'b'时,对字符串执行某些操作的函数。 It can only have one of the two and not both and also only one occurrence of it. 它只能有两个中的一个而不是两个,也只有一个出现。

Because OP's original post wanted to generalize 'a' and 'b' to a sequence of characters list , I interpret his meaning to be he wants an expression that returns True for a string s if and only if s has exactly one occurrence of exactly one element of a list of characters list . 因为OP的原始帖子想要将'a'和'b'概括为一系列字符list ,我将他的意思解释为他想要一个表达式,当一个字符串s返回True ,当且仅当s恰好出现一个字符串时字符list元素list

sum(s.count(char) for char in list) <= 1

In OP's simple example, list = ['a', 'b'] . 在OP的简单示例中, list = ['a', 'b']

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

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