15

在 Python(特别是 Python 3.0,但我认为这并不重要)中,如何轻松地在具有连续字符代码的字符序列上编写循环?我想做这样的伪代码:

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

示例:下面的一个不错的“pythonic”版本怎么样?

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!

亲爱的巫师们(特别是年长的白胡子巫师),也许你能看出我最喜欢的语言曾经是 Pascal。

4

6 回答 6

44

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

>>> from string import ascii_lowercase

然后您可以遍历该字符串中的字符。

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

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

>>> def pangram(str) :
...     return set(ascii_lowercase).issubset(set(str))
于 2009-02-05T03:47:46.843 回答
19

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

for code in range(ord('a'), ord('z') + 1):
     print chr(code)
于 2009-02-05T04:04:39.540 回答
6

你必须抛开 Pascal 主义,以全新的视角学习 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 中缺少哪些字母。

于 2009-02-05T11:00:09.790 回答
2

一个更抽象的答案是这样的:

>>> x="asdf"
>>> for i in range(len(x)):
...     print x[i]
于 2011-08-16T19:32:44.380 回答
1

哈基

method_1 = [chr(x) for x in range(ord('a'), ord('z')+1)]
print(method_1)

整洁的

# this is the recommended method generally 
from string import ascii_lowercase  
method_2 = [x for x in ascii_lowercase]
print(method_2)
于 2021-01-11T10:25:48.240 回答
0

我会写一个类似于 Python 的函数range

def alpha_range(*args):
  if len(args) == 1:
    start, end, step = ord('a'), ord(args[0]), 1
  elif len(args) == 2:
    start, end, step = ord(args[0]), ord(args[1]), 1
  else:
    start, end, step = ord(args[0]), ord(args[1]), args[2]
  return (chr(i) for i in xrange(start, end, step))
于 2009-02-05T06:20:41.980 回答