可以在python中制作字母范围吗?

问题描述 投票:0回答:10

有没有办法在 python 中执行字母范围,如下所示:

for x in range(a,h,)
python python-3.x
10个回答
22
投票

类似:

[chr(i) for i in range(ord('a'),ord('h'))]

将给出要迭代的字母字符列表,然后您可以在循环中使用

for x in [chr(i) for i in range(ord('a'),ord('h'))]:
    print(x)

或者这会起到同样的作用:

for x in map(chr, range(*map(ord,['a', 'h']))):
    print(x)

5
投票

您可以使用

ord()
将字母转换为字符序数并转换回来:

def char_range(start, end, step=1):
    for char in range(ord(start), ord(end), step):
        yield chr(char)

看起来效果很好:

>>> ''.join(char_range('a', 'z'))
    'abcdefghijklmnopqrstuvwxy'

3
投票

没有内置字母范围,但您可以写一个:

def letter_range(start, stop):
    for c in xrange(ord(start), ord(stop)):
        yield chr(c)


for x in letter_range('a', 'h'):
    print x,

打印:

a b c d e f g

3
投票

Emanuele 的解决方案很棒,只要人们只要求一系列单个字符,我承认这就是最初的提问者提出的。 还有一些解决方案可以生成所有多字符组合:如何生成从 aa... 到 zz 的一系列字符串。 然而,我怀疑想要像范围函数这样的字符的人可能希望能够处理生成从“y”到“af”(从“z”滚动到“aa”)的任意范围。 因此,这是一个更通用的解决方案,其中包括指定范围的最后一个成员或其长度的能力。

def strange(start, end_or_len, sequence='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    """Create a generator of a range of 'sequential' strings from
    start to end_or_len if end_or_len is a string or containing
    end_or_len entries if end_or_len is an integer.

    >>> list(strange('D', 'F'))
    ['D', 'E', 'F']
    >>> list(strange('Y', 'AB'))
    ['Y', 'Z', 'AA', 'AB']
    >>> list(strange('Y', 4))
    ['Y', 'Z', 'AA', 'AB']
    >>> list(strange('A', 'BAA', sequence='AB'))
    ['A', 'B', 'AA', 'AB', 'BA', 'BB', 'AAA', 'AAB', 'ABA', 'ABB', 'BAA']
    >>> list(strange('A', 11, sequence='AB'))
    ['A', 'B', 'AA', 'AB', 'BA', 'BB', 'AAA', 'AAB', 'ABA', 'ABB', 'BAA']
    """
    seq_len = len(sequence)
    start_int_list = [sequence.find(c) for c in start]
    if isinstance(end_or_len, int):
        inclusive = True
        end_int_list = list(start_int_list)
        i = len(end_int_list) - 1
        end_int_list[i] += end_or_len - 1
        while end_int_list[i] >= seq_len:
            j = end_int_list[i] // seq_len
            end_int_list[i] = end_int_list[i] % seq_len
            if i == 0:
                end_int_list.insert(0, j-1)
            else:
                i -= 1
                end_int_list[i] += j
    else:
        end_int_list = [sequence.find(c) for c in end_or_len]
    while len(start_int_list) < len(end_int_list) or start_int_list <= end_int_list:
        yield ''.join([sequence[i] for i in start_int_list])
        i = len(start_int_list)-1
        start_int_list[i] += 1
        while start_int_list[i] >= seq_len:
            start_int_list[i] = 0
            if i == 0:
                start_int_list.insert(0,0)
            else:
                i -= 1
                start_int_list[i] += 1


if __name__ =='__main__':
    import doctest
    doctest.testmod()

2
投票
import string

def letter_range(f,l,al = string.ascii_lowercase):
    for x in al[al.index(f):al.index(l)]:
        yield x

print ' '.join(letter_range('a','h'))

结果

a b c d e f g

2
投票

这至少对我来说更容易阅读/理解(并且您可以轻松自定义包含哪些字母以及按什么顺序):

letters = 'abcdefghijklmnopqrstuvwxyz'
for each in letters:
    print each

result:
a
b
c
...
z

1
投票

对已经预先安排好的列表进行切片怎么样?

import string

s = string.ascii_lowercase
print( s[ s.index('b'):s.index('o')+1 ] )

0
投票

Malcom 的示例效果很好,但由于 Python 列表比较的工作方式存在一些小问题。 如果'A'到“Z”或某些字符到“ZZ”或“ZZZ”将导致错误的迭代。

这里是“AA”< "Z" or "AAA" < "ZZ" will become false.

在 Python 中,与“<" or ">”运算符相比,[0,0,0] 小于 [1,1]。

所以低于线

while len(start_int_list) < len(end_int_list) or start_int_list <= end_int_list:

应该重写如下

while len(start_int_list) < len(end_int_list) or\
        ( len(start_int_list) == len(end_int_list) and start_int_list <= end_int_list):

这里解释得很好 https://docs.python.org/3/tutorial/datastructs.html#comparing-sequences-and-other-types

我重写了下面的代码示例。

def strange(start, end_or_len, sequence='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):

    seq_len = len(sequence)
    start_int_list = [sequence.find(c) for c in start]
    if isinstance(end_or_len, int):
        inclusive = True
        end_int_list = list(start_int_list)
        i = len(end_int_list) - 1
        end_int_list[i] += end_or_len - 1
        while end_int_list[i] >= seq_len:
            j = end_int_list[i] // seq_len
            end_int_list[i] = end_int_list[i] % seq_len
            if i == 0:
                end_int_list.insert(0, j-1)
            else:
                i -= 1
                end_int_list[i] += j
    else:
        end_int_list = [sequence.find(c) for c in end_or_len]

    while len(start_int_list) < len(end_int_list) or\
         (len(start_int_list) == len(end_int_list) and start_int_list <= end_int_list):**
        yield ''.join([sequence[i] for i in start_int_list])
        i = len(start_int_list)-1
        start_int_list[i] += 1
        while start_int_list[i] >= seq_len:
            start_int_list[i] = 0
            if i == 0:
                start_int_list.insert(0,0)
            else:
               i -= 1
                start_int_list[i] += 1

无论如何,Malcom 的代码示例很好地说明了 Python 中迭代器的工作原理。


0
投票

有时,一个简单的解决方案可能会被过度设计。 如果您知道所需的字母范围,为什么不直接使用:

for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    print(letter)

甚至:

start = 4
end = 9
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for letter in alphabet[start:end]:
    print(letter)

在第二个示例中,我演示了一种从固定列表中选择所需字母数的简单方法。


0
投票

我编写了一个名为 Alphabetic 的 Python 包,它允许您通过名称检索语言的字母表,而不是指定范围。要检索英文字母,请执行以下步骤:

首先,通过以下方式安装package

pip install alphabetic

接下来,写下以下内容:

from alphabetic import WritingSystem

# Create a WritingSystem instance to access all core functions
ws = WritingSystem()

# Retrieve the alphabet of the language
ws.by_language(ws.Language.English)

# Result
{'English': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']}

如果您只需要漂亮的输出打印,请使用

pretty_print
函数:

ws.pretty_print(ws.by_language(ws.Language.English))

# Result:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z

除了英语之外,您还可以从此处列出的多种语言中进行选择。

© www.soinside.com 2019 - 2024. All rights reserved.