如何检查字符是否在列表中重复

2024-09-27 07:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

def check(inp, chk):
    if chk in inp:
        print("Yes")
    else:
        print("No")

inp = [int(x) for x in input().split()]
chk = input("Enter a character to check: ")

check(inp, chk)

1 2 3 4 5 6 7 8 9

输入要检查的字符:1

没有

当我给列表中的任何字符时,它都会说“不”

这里面有什么错误?你知道吗


Tags: noinforinputifdefcheck字符
1条回答
网友
1楼 · 发布于 2024-09-27 07:27:54

您可以通过使用^{}来实现这一点,它返回一个dictobject,其中包含迭代器中每个元素的计数。你知道吗

下面是检查Counter对象重复的示例函数:

def check_repeatition(num, counter):
    count = counter.get(num)  # returns `None` if `num` not found
    if count == 1:
        print('Non repeated number')
    elif count == None:
        print('Number not found')
    else:
        print('Repeated Number')

运行示例:

>>> from collections import Counter
#                 v           v  repeated
>>> my_num_str = '1 2 3 4 5 6 1 7 8 9'

# Convert number string to `list` of `int` numbers
>>> num_counter = Counter(map(int, my_num_str.split()))

# Two occurrence of `1` in the string
>>> check_repeatition(1, num_counter)
Repeated Number

# One occurrence of `2` in the string
>>> check_repeatition(2, num_counter)
Non repeated number

# `0` not present in the string
>>> check_repeatition(0, num_counter)
Number not found

代码的问题是您正在使用in运算符检查列表中是否存在数字。您的代码没有检查数字是否重复。此外,您还需要通过在python3.x中使用chk = int(chk)作为input(...)返回str来将chk类型转换为int

相关问题 更多 >

    热门问题