繁体   English   中英

Python - 计算字符串中不同数字的数量

[英]Python - Count Numbers of Different Digits in String

我对 Python 很陌生,请帮忙。

我只能使用 if else 语句,不能使用循环或任何类似的东西。

该程序要求用户提供一个字符串。 它计算字符串中不同数字的数量。 例如 a11111a1a1 包含一个数字,而 a1s2d1d2d1d2d1 包含 2 个数字。

例子:

% python3 countNumbers.py
enter string: qwerty
there are no digits in string: "qwerty"

% python3 countNumbers.py
enter string: asdf1sdfg
there is one digit in string: "asdf1sdfg"

% python3 countNumbers.py
enter string: as1as2as333333
there are 3 different digits in string: "as1as2as333333"

% python3 countNumbers.py
enter string: a0123456789x
there are 10 different digits in string: "a0123456789x"
num = input("enter string: ")
count = 0

if "0" in num:
    count = count + 1
if "1" in num:
    count = count + 1
if "2" in num:
    count = count + 1
if "3" in num:
    count = count + 1
if "4" in num:
    count = count + 1
if "5" in num:
    count = count + 1
if "6" in num:
    count = count + 1
if "7" in num:
    count = count + 1
if "8" in num:
    count = count + 1
if "9" in num:
    count = count + 1

if count >= 1:
    print("there is one digit in string: ", num)
elif count >= 2:
    print("there are two digits in string: ", num)
else:
    print("there are no digits in string: ", num)

这是使用正则表达式,因此导入正则表达式库:

import re

使用以下 Python 查找单个数字:

a = re.findall('\d', string)

如果您想一起使用多个数字,请使用:

a = re.findall('\d+', string)

然后使用以下内容计算 ( len ) set (使其唯一):

len(set(a))

你可以这样做:

len(set(a).intersection(map(str, range(10))))

一个没有re班轮,使用普通的liststr操作

x='a1s2d1d2d1d2d1'
>>> sum( i.isdigit() for i in list(set(list(x))) )
2
>>>

分解:将string转换为list ,然后将set转换为list ,将删除重复项,然后计算数字。

>>>
>>> l = list(set(list(x)))
>>> sum( i.isdigit() for i in l )
2

注意:这在一个衬垫内使用循环

好吧,如果您知道循环,它会容易得多,并且看起来会像 Python 一样。 但是,我在这里修改了您的代码,这里是使用“ if-else ”语句和“ sets ”的解决方案

s = set()
if "0" in num:
    s.add(0)
if "1" in num:
    s.add(1)
if "2" in num:
    s.add(2)
if "3" in num:
    s.add(3)
if "4" in num:
    s.add(4)
if "5" in num:
    s.add(5)
if "6" in num:
    s.add(6)
if "7" in num:
    s.add(7)
if "8" in num:
    s.add(8)
if "9" in num:
    s.add(9)
print(len(s))

这里是

count_dict = {}
for i in range(0, 10):
    if i in num and i not in count_dict:
        count_dict[i] = 1 # just adding the integer to a dict
    else:
        continue


print('there are {} different integers in string {}'.format(len(count_dict), num)
num=input()
count=0

for i in num:
    if i in '0123456789':
        count+=1

print(count)

您可以在一行中使用“in”

暂无
暂无

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

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