简体   繁体   English

什么是python相当于perl“a”..“azc”

[英]What is the python equivalent to perl “a”..“azc”

In perl, to get a list of all strings from "a" to "azc", to only thing to do is using the range operator: 在perl中,要获取从“a”到“azc”的所有字符串的列表,要做的只是使用范围运算符:

perl -le 'print "a".."azc"'

What I want is a list of strings: 我想要的是一个字符串列表:

["a", "b", ..., "z", "aa", ..., "az" ,"ba", ..., "azc"]

I suppose I can use ord and chr , looping over and over, this is simple to get for "a" to "z", eg: 我想我可以使用ordchr ,一遍又一遍地循环,这很容易得到“a”到“z”,例如:

>>> [chr(c) for c in range(ord("a"), ord("z") + 1)]
['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']

But a bit more complex for my case, here. 但对我的情况来说有点复杂,在这里。

Thanks for any help ! 谢谢你的帮助 !

A suggestion purely based on iterators: 一个纯粹基于迭代器的建议:

import string
import itertools

def string_range(letters=string.ascii_lowercase, start="a", end="z"):
    return itertools.takewhile(end.__ne__, itertools.dropwhile(start.__ne__, (x for i in itertools.count(1) for x in itertools.imap("".join, itertools.product(letters, repeat=i)))))

print list(string_range(end="azc"))

Generator version: 发电机版本:

from string import ascii_lowercase
from itertools import product

def letterrange(last):
    for k in range(len(last)):
        for x in product(ascii_lowercase, repeat=k+1):
            result = ''.join(x)
            yield result
            if result == last:
                return

EDIT: @ihightower asks in the comments: 编辑: @ihightower在评论中提问:

I have no idea what I should do if I want to print from 'b' to 'azc'. 如果我想从'b'打印到'azc',我不知道该怎么办。

So you want to start with something other than 'a' . 所以你想从'a'以外'a'东西开始。 Just discard anything before the start value: 只需丢弃起始值之前的任何内容:

def letterrange(first, last):
    for k in range(len(last)):
        for x in product(ascii_lowercase, repeat=k+1):
            result = ''.join(x)
            if first:
                if first != result:
                    continue
                else:
                    first = None
            yield result
            if result == last:
                return

Use the product call in itertools, and ascii_letters from string. 在itertools中使用product调用,在string中使用ascii_letters。

from string import ascii_letters
from itertools import product

if __name__ == '__main__':
    values = []
    for i in xrange(1, 4):
        values += [''.join(x) for x in product(ascii_letters[:26], repeat=i)]

    print values

Here's a better way to do it, though you need a conversion function: 虽然您需要转换功能,但这是一种更好的方法:

for i in xrange(int('a', 36), int('azd', 36)):
    if base36encode(i).isalpha():
        print base36encode(i, lower=True)

And here's your function (thank you Wikipedia ): 这是你的功能(谢谢维基百科 ):

def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', lower=False):
    '''
    Convert positive integer to a base36 string.
    '''
    if lower:
        alphabet = alphabet.lower()
    if not isinstance(number, (int, long)):
        raise TypeError('number must be an integer')
    if number < 0:
        raise ValueError('number must be positive')

    # Special case for small numbers
    if number < 36:
        return alphabet[number]

    base36 = ''
    while number != 0:
        number, i = divmod(number, 36)
        base36 = alphabet[i] + base36

    return base36

I tacked on the lowercase conversion option, just in case you wanted that. 我添加了小写转换选项,以防你想要它。

I generalized the accepted answer to be able to start middle and to use other than lowercase: 我将接受的答案概括为能够从中间开始并使用除小写以外的其他答案:

from string import ascii_lowercase, ascii_uppercase
from itertools import product

def letter_range(first, last, letters=ascii_lowercase):
    for k in range(len(first), len(last)):
        for x in product(letters, repeat=k+1):
            result = ''.join(x)
            if len(x) != len(first) or result >= first:
                yield result
                if result == last:
                    return
print list(letter_range('a', 'zzz'))
print list(letter_range('BA', 'DZA', ascii_uppercase))
def strrange(end):
    values = []
    for i in range(1, len(end) + 1):
        values += [''.join(x) for x in product(ascii_lowercase, repeat=i)]
    return values[:values.index(end) + 1]

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

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