Python:循环连续字符?

2024-05-03 19:18:56 发布

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

在Python中(特别是Python 3.0,但我认为这无关紧要),如何轻松地在具有连续字符代码的字符序列上编写循环?我想做一些类似于伪代码的事情:

for Ch from 'a' to 'z' inclusive: #
    f(Ch)

一个不错的“Python”版本怎么样?

def Pangram(Str):
    ''' Returns True if Str contains the whole alphabet, else False '''
    for Ch from 'a' to 'z' inclusive: #
        M[Ch] = False
    for J in range(len(Str)):
        Ch = lower(Str[J])
        if 'a' <= Ch <= 'z':
            M[Ch] = True
    return reduce(and, M['a'] to M['z'] inclusive) #

标记的行是伪代码。当然reduce()是真正的Python!

亲爱的巫师们(特别是老的,灰白胡子的巫师们),也许你可以看出我最喜欢的语言是帕斯卡语。


Tags: to代码from版本falsetruereducefor
3条回答

用你需要的所有字符来迭代一个常量是非常愚蠢的。但是,如果您不想导入任何内容,并且只使用Unicode,请使用内置的ord()及其逆chr()。

for code in range(ord('a'), ord('z') + 1):
     print chr(code)

字符串模块中有一个名为ascii_lowercase的常量,请尝试:

>>> from string import ascii_lowercase

然后您可以迭代该字符串中的字符。

>>> for i in ascii_lowercase :
...     f(i)

对于pangram问题,有一种非常简单的方法可以确定字符串是否包含字母表中的所有字母。像以前一样使用ascii_小写

>>> def pangram(str) :
...     return set(ascii_lowercase).issubset(set(str))

你必须抛开帕斯卡主义,以全新的视角学习Python。

>>> ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> def pangram( source ):
    return all(c in source for c in ascii_lowercase)

>>> pangram('hi mom')
False
>>> pangram(ascii_lowercase)
True

通过限制自己使用Pascal提供的功能,您就错过了Python提供的功能。

还有。。。尽量避免reduce。它常常导致可怕的性能问题。


编辑。这是另一个公式;这个公式实现了集合交集。

>>> def pangram( source ):
>>>     notused= [ c for c in ascii_lowercase if c not in source ]
>>>     return len(notused) == 0

这一个给你一个诊断信息,用于确定候选pangram缺少哪些字母。

相关问题 更多 >