如何检查天气,在列表Python中重复一个字符

时间:2017-05-01 10:00:32

标签: python python-3.x

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

没有

当我给出列表中的任何字符时,它会说不。

这有什么错误?

1 个答案:

答案 0 :(得分:0)

您可以通过使用collections.Counter来实现此目的,该StackExchange Redis Connection String返回一个dict object,其中包含迭代器中每个元素的计数。

以下是检查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运算符检查列表中是否存在该号码。您的代码不会检查重复的数字。此外,您还需要使用chkint输入chk = int(chk),因为input(...)返回{ Python 3.x中的{1}}