如果字符串以某个字符开头并且在字符串中重复,我会尝试将计数加一。这是我的代码
def stringMatch(list1, char):
count = 0
for i in range(len(list1)):
if char == list1[i][:]:
count = count + 1
print(list1[i], count)
对于输入 list1 = ['cat', 'dog', 'corn']
和 char = 'c'
输出应该是
cat 1
corn 1
最佳答案
在您的代码中,您使用if char == list1[i][:]
。这会导致您的问题。
list1[i][:]
与 list1[i]
相同,这实际上不是您想要做的。您不想查看 list1[i]
是否为 char
;相反,您想知道 list1[i]
包含 char
。您可以通过多种方式来实现这一目标。以下是三个:
list1[i]中的字符
- 这个for循环:
found = False
for c in list1[i]:
if c == char:
found = True
break
如果有(list1[i] 中的 c 为 char==c)
无论如何,这就是我要做的:
def stringMatch(L, char):
counts = (char in word for word in L) # compute the counts of `char` in each list item
for word, count in zip(L, counts):
if not count: continue
print(word, count)
关于python - 只打印包含特定字符的列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599481/